leetcode No145. Binary Tree Postorder Traversal

Posted Dufre.WC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode No145. Binary Tree Postorder Traversal相关的知识,希望对你有一定的参考价值。

Question

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

Example:

Input: [1,null,2,3]
   1
    \\
     2
    /
   3

Output: [3,2,1]

Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?

Algorithm

二叉树后序遍历
非递归方法:
法一:用一个pre记录被访问过的节点
法二:其实是根-右-左的倒序

Code

法一(C++)

/**
 * Definition for a binary tree node.
 * struct TreeNode 
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) 
 * ;
 */
class Solution 
public:
    vector<int> postorderTraversal(TreeNode* root) 
        vector<int> res;
        stack<TreeNode*> s;
        TreeNode* cur = root;
        TreeNode* pre = NULL;
        
        while(cur)
            s.push(cur);
            cur = cur->left;
        
        while(!s.empty())
            cur = s.top();
            s.pop();
            if(cur->right==NULL || cur->right==pre)
                res.push_back(cur->val);
                pre = cur;
            
            else
                s.push(cur);
                cur = cur->right;
                while(cur)
                    s.push(cur);
                    cur = cur->left;
                
            
        
        
        return res;
    
;

法二(Python)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res, stack = [], [root,]
        while stack:
            cur = stack.pop()
            if cur:
                res.append(cur.val);
                stack.append(cur.left);
                stack.append(cur.right);
                   
        return res[::-1]

以上是关于leetcode No145. Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 145. Binary Tree Postorder Traversal

LeetCode145. Binary Tree Postorder Traversal 解题报告

LeetCode 145:Binary Tree Postorder Traversal

LeetCode 145: Binary Tree Postorder Traversal

leetcode145. Binary Tree Postorder Traversal

LeetCode OJ 145. Binary Tree Postorder Traversal