您的位置:首页 > 其它

LeetCode 145 Binary Tree Postorder Traversal (后序遍历二叉树)

2016-08-31 10:02 399 查看
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]
.

Note: Recursive solution is trivial, could you do it iteratively?

题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/

递归:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {

public void DFS(TreeNode root, List<Integer> ans) {
if(root == null) {
return;
}
DFS(root.left, ans);
DFS(root.right, ans);
ans.add(root.val);
}

public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
DFS(root, ans);
return ans;
}
}

非递归:后序遍历左右中,考虑到栈的先进先出,故先将右子树压栈,两种情况记录答案出栈,1是遇到叶子,2是父节点的子节点已经被访问过,根据压栈顺序,可以保证这样可以完成后序遍历

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {

public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
if(root != null) {
stk.push(root);
}
TreeNode cur = null;
TreeNode pre = null;
while(!stk.empty()) {
cur = stk.peek();
if(cur.left == null && cur.right == null) {
ans.add(cur.val);
pre = cur;
stk.pop();
}
else if(pre != null && (cur.left == pre || cur.right == pre)) {
ans.add(cur.val);
pre = cur;
stk.pop();
}
else {
if(cur.right != null) {
stk.push(cur.right);
}
if(cur.left != null) {
stk.push(cur.left);
}
}
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐