补数据结构算法中,发现Leetcode也有遍历二叉树的习题,特来码一下
前序
创建辅助栈,每次迭代弹出根节点,并按照右 左的顺序压入栈,故出栈时为,根 左 右,符合前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack=new Stack();
List<Integer> list=new ArrayList<>();
if(root==null)
return list;
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.pop();
list.add(node.val);
if(node.right!=null) stack.push(node.right);
if(node.left!=null) stack.push(node.left);
}
return list;
}
}
中序
同样创建辅助栈,弹出顺序按照压入顺序的相反
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
List<Integer> list=new ArrayList<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
list.add(root.val);
root=root.right;
}
return list;
}
}
后序
需要两个栈,栈2用来压入栈一弹出的元素,前序为根左右,将其转化为根右左,也就是压入的时候先压入左子树,再压入柚子树。因为后序为左右根,因此栈1只需要按顺序弹出即可实现(先进后出)
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
stack1.push(root);
while(!stack1.isEmpty()){
TreeNode node=stack1.pop();
if(node!=null){
stack2.push(node.val);
stack1.push(node.left);
stack1.push(node.right);
}
}
List<Integer> list=new ArrayList<>();
while(!stack2.isEmpty()){
list.add(stack2.pop());
}
return list;
}
}