Tc的专栏

待重头,收拾旧山河,朝天阙

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

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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/52381908
个人分类: Leetcode Hard
所属专栏: LeetCode 算法题
上一篇shell脚本 制定文件的批量复制
下一篇LeetCode 79 Word Search (DFS)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭