前序:
两种思想:
1. 类似中序遍历,从上到左下先把当前结点的val加入结果列表,再push结点进栈,直至左节点为空,再把右子结点push,循环
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
while( node != null|| !stack.isEmpty()){
while(node!=null){
list.add(node.val);
stack.push(node);
node = node.left;
}
TreeNode curr = stack.pop();
node = curr.right;
}
return list;
}
2. 栈的特点是后进先出,于是,先把当前结点的val加入结果列表,再push当前结点的右子结点进栈,再push当前结点的左子结点
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root==null) return list;
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
stack.push(node);
while(!stack.isEmpty()){
TreeNode curr = stack.pop();
list.add(curr.val);
if(curr.right!=null){
stack.push(curr.right);
}
if(curr.left!=null){
stack.push(curr.left);
}
}
return list;
}
中序:
核心思想:从上到左下不断地往栈里push结点,直到左子结点为空,然后从栈里pop元素,把val加入结果列表,把右子结点push,循环
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
while(node!=null || !stack.isEmpty()){
while(node!=null){
stack.push(node);
node = node.left;
}
TreeNode curr = stack.pop();
list.add(curr.val);
node = curr.right;
}
return list;
}
后序
核心思想:
用curr标记当前退出的节点是什么。
后序遍历的过程中在遍历完左子树跟右子树后,peek都会回到根结点。所以当前不管是从左子树还是右子树回到根结点都不应该再操作了,应该退回上层。
如果是从右边再返回根结点,应该回到上层。
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root==null) return list;
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
TreeNode curr = root;
while(!stack.isEmpty()){
TreeNode peek = stack.peek();
if(peek.left!=null && peek.left!=curr && peek.right!=curr ){
stack.push(peek.left);
}else if(peek.right!=null && peek.right!=curr){
stack.push(peek.right);
}else{
curr = stack.pop();
list.add(curr.val);
}
}
return list;
}
方法二:
更好理解一点
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode pre = null;
while(root!=null || !stack.isEmpty() ){
while(root!=null){
stack.push(root);
root = root.left;
}
TreeNode curr = stack.pop();
if(curr.right==null || curr.right == pre ){
list.add(curr.val);
pre = curr;
}else{
stack.push(curr);
root = curr.right;
}
}
return list;
}