Preorder Iterator

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 Iterator

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记住前一个节点的值,然后再和当前节点大小比较

有一类树的题目是和path相关的,比如求满足条件的最长path,和最大的path等等。这一类的题目一般需要写一个helper recursion function来返回经过某节点的单边最长path(或最大path和等等),还需要一个全局变量来记录全局的最大值
124. Binary Tree Maximum Path Sum
543. Diameter of Binary Tree
687. Longest Univalue Path

解决树的问题一般有两种方式:bottom to top和top to bottom。bottom to top是先处理当前节点,再处理当前节点的左右子节点,在写recursion时一般要将当前状态作为参数传递给子节点。top to bottom是先处理左右子树,再利用左右子树处理后的状态来处理当前节点,一般将左右子树处理后的状态作为结果直接返回给上一层。
top to bottom:

bottom to top:
652. Find Duplicate Subtrees
606. Construct String from Binary Tree

有一些和delete相关的树的题目,一般用bottom to top解决,先处理左右子树,然后根据左右子树以及自身的状态来决定是否删除自身
814. Binary Tree Pruning
450. Delete Node in a BST

BST问题考虑inorder遍历, 或当需要top to bottom时从root.val值大小入手,选择走左子节点或右子节点

Serialize and Deserialize Tree部分是高频题


我想做个正常人
1 声望2 粉丝