Binary Tree Postorder Traversal

来源:互联网 发布:各班级出勤率数据图表 编辑:程序博客网 时间:2024/05/17 06:54

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].

思路:后序遍历是 左子树-根节点-右子树,递归的方式很简单,但是迭代的话,需要利用栈来存储遍历过程中的结点,存入栈的顺序是根节点,右子树,左子树,同时也需要记录当前后序遍历序列中最后一个结点,如果后序遍历序列中最后一次打印的结点是当前结点的左子树或者右子树的时候或者当前结点是叶子结点,就说明当前结点的左右子树已经遍历完成了,可以输出当前结点了;否则,说明当前结点的左子树或者右子树还没有遍历完,当前不能输出当前结点,继续往栈中加入当前结点的右子树和左子树。注意,往栈中加入结点的时候,要先加入右子树结点,再加入左子树结点。

public class Solution {    public List<Integer> postorderTraversal(TreeNode root) {         List<Integer> result=new ArrayList<Integer>();         if(root==null) return result;         Stack<TreeNode> temp=new Stack<TreeNode>();         temp.push(root);        TreeNode pre=null;         while(!temp.empty())        {            TreeNode node=temp.peek();            if((pre==node.left||pre==node.right)||(node.left==null&&node.right==null))            {                temp.pop();                result.add(node.val);                pre=node;            }            else{             if(node.right!=null) temp.push(node.right);              if(node.left!=null) temp.push(node.left);            }        }            return result;    }}

下面的代码虽然可以得到正确结果,但是运行时间太长,是先把后序遍历的反序放入集合中,然后将集合逆置就是最终得到的结果

public class Solution {    public List<Integer> postorderTraversal(TreeNode root) {         List<Integer> result=new ArrayList<Integer>();         if(root==null) return result;         Stack<TreeNode> temp=new Stack<TreeNode>();         temp.push(root);         while(!temp.empty())        {            TreeNode node=temp.pop();            result.add(node.val);            if(node.left!=null) temp.push(node.left);            if(node.right!=null) temp.push(node.right);        }       Collections.reverse(result);            return result;    }}
0 0
原创粉丝点击