关闭

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

标签: leetcode后序遍历二叉树
560人阅读 评论(0) 收藏 举报
分类:

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;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:604561次
    • 积分:13838
    • 等级:
    • 排名:第940名
    • 原创:803篇
    • 转载:7篇
    • 译文:0篇
    • 评论:120条
    博客专栏