三序遍歷以及Vertical Order

Binary Tree Preorder Traversal

  • preorder 直接用 stack;
  • inorder 用 stack + cur;
  • postorder 用 stack + cur + prev;
  • 遞歸 ✓
  • 迭代 ✓
  • parent ✓
  • 複雜度 ✓

迭代的寫法過於 trivial 就不細說了,記得因爲 stack 先入後出的特點,push 的時候先 push 右邊的就行。

Binary Tree Inorder Traversal

  • inorder 用 stack + cur;

stack 寫法要記住的細節是,兩個while循環裏面都是(cur != null)


 public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();

        TreeNode cur = root;(1)準備一插到底(左子樹)
        
	while(cur != null || !stack.isEmpty()){(2)
            
	    while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }(3)
            
            TreeNode node = stack.pop();
            list.add(node.val);
            
	    cur = node.right;  (4)
        }

        return list;
    }
}

Inorder Successor in BST

因此在 BST 裏面,確定起來就很簡單了,從 root 往下走,如果當前結點root的val > p.val,左拐。每次往左拐的時候,存一下,記錄着最近一個看到的比 p.val 大的 node 就行了。如果root.val > p.val,右拐。

public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode rst = null;

        while(root != null){
            if(root.val > p.val){
                rst = root;
                root = root.left;
            } else {
                root = root.right;
            }
        }

        return rst;
    }
}

Inorder Predecessor in BST

這次往左走的時候不記,往右走的時候記,就行了。

public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode rst = null;

        while(root != null){
            if(root.val > p.val){
                root = root.left;
            } else {
                rst = root;
                root = root.right;
            }
        }

        return rst;
    }
}

Binary Tree Postorder Traversal

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
Stack<TreeNode> s = new Stack(), path = new Stack();
s.push(root);
while(!s.isEmpty()){
TreeNode cur = s.peek();
if(!path.isEmpty() && path.peek() == root){             which means we hit t
res.add(root.val);
path.pop();
s.pop();
} else {
path.push(root);
if(root.right != null) 
s.push(root.right);
if(root.left != null) 
s.push(root.left);
}
}
return res;
}

這裏每次當path.peek != root的時候,需要path.push(root)記錄我們是怎麼到當前這一步的。

然後還需要往s.push一個root.right和root.left以便繼續遍歷。

When top elements of both stacks are equal. (Which means we hit a deadend, and need to turn back)
  • Pop from both stacks.









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章