三序遍历以及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.









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值