LeetCode—145. Binary Tree Postorder Traversal
题目
https://leetcode.com/problems/binary-tree-postorder-traversal/description/
后序遍历二叉树。
思路及解法
1.递归
2.非递归,栈
迭代的稍微复杂一些 总体上和前面的解法是一样的 不过这边要先访问左右节点,同样还是以左节点作为主线,不过这里要增加一个栈记录每个节点的右节点是否已经被访问过,只有当左右节点都被访问的前提下才能访问根节点
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
postOrder(root);
return list;
}
public void postOrder(TreeNode node){
if(node==null) return;
if(node.left!=null){
postOrder(node.left);
}
if(node.right!=null){
postOrder(node.right);
}
list.add(node.val);
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root==null) return res;
helper(root, res);
return res;
}
public void helper(TreeNode node, List<Integer> list){
if(node==null) return;
helper(node.left, list);
helper(node.right, list);
list.add(node.val);
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root==null)
return res;
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
s1.push(root);
while(!s1.isEmpty()){
TreeNode node = s1.pop();
s2.push(node);
if(node.left!=null)
s1.push(node.left);
if(node.right!=null)
s1.push(node.right);
}
while(!s2.isEmpty()){
res.add(s2.pop().val);
}
return res;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> nodeStack = new Stack<>();
Stack<Integer> nodeState = new Stack<>();
if(root == null) return list;
else{
nodeStack.push(root);
nodeState.push(0);
root = root.left;
}
while(!nodeStack.isEmpty()){
while(root!=null){
nodeStack.push(root);
nodeState.push(0);
root = root.left;
}//当这个循环跳出的时候 说明nodeStak栈顶的那个节点没有左节点
if(nodeState.peek()==1){//如果这时候已经访问过右节点了 这时候就可以访问根节点
list.add(nodeStack.pop().val);
nodeState.pop();//把根节点对应的状态值去除
}else{//访问右节点
root = nodeStack.peek().right;
nodeState.pop();//更改状态值 由0变1
nodeState.push(1);
}
}
return list;
}
}