您的位置:首页 > 其它

二叉树后续遍历(递归+非递归)

2016-04-15 11:16 169 查看
二叉树后续遍历:左-右-中

树节点类

class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}

}


递归实现
/*
* 二叉树后续遍历
*
*/

public class PostorderTraversal {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
// write your code here
ArrayList<Integer> arr = new ArrayList<Integer>();
inorder(arr,root);
return arr;

}
public ArrayList<Integer> inorder(ArrayList<Integer> arr, TreeNode root)
{
if(root == null)
return arr;
if(root!=null)
{
if(root.left!=null)
{
arr = inorder(arr, root.left);
}
if(root.right!=null)
{
arr = inorder(arr, root.right);
}
arr.add(root.val);
}
return arr;

}

}


非递归实现
后续遍历非递归实现有点复杂。思路是设置一个标志位,在不到根节点时候便一直循环,首先按照root.left顺序将节点依次压入List中,直到叶子节点。此时List最后一个元素为叶子节点的父节点。接着循环判断此叶子节点为父节点的左子树还是右子树,并将此叶子节点放入result中。循环右回到一开始。

public class PostorderTraversal1 {

public ArrayList<Integer> postorderTraversal(TreeNode root) {
// write your code here
ArrayList<Integer> arr = new ArrayList<Integer>();
ArrayList<TreeNode> p = new ArrayList<TreeNode>();
int flag = 1;
while(flag ==1)
{
while(root.left!=null || root.right!=null)
{
if(root.left!=null)
{
p.add(root);
root = root.left;
}
else {
p.add(root);
root = root.right;
}
}
TreeNode tnNode = p.get(p.size()-1);
while(root == tnNode.right || tnNode.right==null)
{
arr.add(root.val);
p.remove(p.size()-1);
if(p.size()==0)
{
arr.add(tnNode.val);
flag = 0;
break;
}
root = tnNode;
tnNode = p.get(p.size()-1);
}
if(root ==tnNode.left && tnNode.right!=null)
{
arr.add(root.val);
root = tnNode.right;

}
}
return arr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: