Leetcode複習小結:Tree

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部分是高頻題變量

相關文章
相關標籤/搜索