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) {s.push(root.right);
if(root.left != null)
s.push(root.left);
这里每次当path.peek != root的时候,需要path.push(root)记录我们是怎么到当前这一步的。
然后还需要往s.push一个root.right和root.left以便继续遍历。
Pop
fromboth
stacks.