Preorder Iteratornode
class BSTIterator { Stack<TreeNode> s = new Stack<>(); public BSTIterator(TreeNode root) { if (root != null) s.push(root); } public int next() { TreeNode cur = s.pop(); if (cur.right != null) s.push(cur.right); if (cur.left != null) s.push(cur.left); return cur.val; } public boolean hasNext() { return (!s.isEmpty()); } }
Postorder Iteratorcode
class BSTIterator { Stack<TreeNode> s = new Stack<>(); public BSTIterator(TreeNode root) { push(root); } public int next() { TreeNode cur = s.pop(); if (!s.isEmpty()) { TreeNode top = s.peek(); if (cur == top.left) push(top.right); } return cur.val; } public boolean hasNext() { return (!s.isEmpty()); } public void push(TreeNode node) { while (node != null) { s.push(node); if (node.left != null) node = node.left; else node = node.right; } } }
Inorder Iterator排序
class BSTIterator { Stack<TreeNode> s = new Stack<>(); public BSTIterator(TreeNode root) { push(root); } /** @return the next smallest number */ public int next() { TreeNode cur = s.pop(); push(cur.right); return cur.val; } /** @return whether we have a next smallest number */ public boolean hasNext() { return !s.isEmpty(); } public void push(TreeNode node) { while (node != null) { s.push(node); node = node.left; } } }
98. Validate Binary Search Tree
判断一个树是不是BST能够从两个角度入手:
1 左右子树均为BST且根节点值大于左子树上的最大值,小于右子树的最小值
这个角度有两种写法,一种是top-bottom,也就是先判断左右子树是不是BST再求出左右子树最大和最小值,和根节点作比较;另外一种是bottom-top,直接把该节点要想成为BST所要知足的取值范围传进去
2 BST的inorder遍历是从小到大排序的,这种写法须要一个prev记住前一个节点的值,而后再和当前节点大小比较leetcode
有一类树的题目是和path相关的,好比求知足条件的最长path,和最大的path等等。这一类的题目通常须要写一个helper recursion function来返回通过某节点的单边最长path(或最大path和等等),还须要一个全局变量来记录全局的最大值
124. Binary Tree Maximum Path Sum
543. Diameter of Binary Tree
687. Longest Univalue Pathget
解决树的问题通常有两种方式:bottom to top和top to bottom。bottom to top是先处理当前节点,再处理当前节点的左右子节点,在写recursion时通常要将当前状态做为参数传递给子节点。top to bottom是先处理左右子树,再利用左右子树处理后的状态来处理当前节点,通常将左右子树处理后的状态做为结果直接返回给上一层。
top to bottom:string
bottom to top:
652. Find Duplicate Subtrees
606. Construct String from Binary Treeio
有一些和delete相关的树的题目,通常用bottom to top解决,先处理左右子树,而后根据左右子树以及自身的状态来决定是否删除自身
814. Binary Tree Pruning
450. Delete Node in a BSTfunction
BST问题考虑inorder遍历, 或当须要top to bottom时从root.val值大小入手,选择走左子节点或右子节点class
Serialize and Deserialize Tree部分是高频题变量