145. Binary Tree Postorder Traversal(python+cpp)

题目:

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

解释:
二叉树的后序遍历。

python代码:

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

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        def post(root,result):
            if root==None:
                return None
            post(root.left,result)
            post(root.right,result)
            result.append(root.val)
        result=[]
        post(root,result)
        return result

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> result;
        post(root,result);
        return result;
    }
    void post(TreeNode*root,vector<int>&result)
    {
        if (root)
        {
            post(root->left,result);
            post(root->right,result);
            result.push_back(root->val);
        }
    }
};

非递归解法:
双压栈解法:
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]
        """
        #后续遍历的非递归解法,双压栈版
        result=[]
        stack=[]
        if not root:
            return result
        stack.append(root)
        stack.append(root)
        while (stack):
            cur=stack.pop()
            if(stack and cur==stack[-1]):
                if (cur.right):
                    stack.append(cur.right)
                    stack.append(cur.right)
                if (cur.left):
                    stack.append(cur.left)
                    stack.append(cur.left)
            else:
                result.append(cur.val)
        return result    

c++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<stack>
using namespace std;
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>result;
        stack<TreeNode*>_stack;
        if (!root)
            return result;
        TreeNode*cur;
        _stack.push(root);
        _stack.push(root);
        while(!_stack.empty())
        {
            cur=_stack.top();
            _stack.pop();
            if(!_stack.empty() && cur==_stack.top())
            {
                if(cur->right)
                {
                    _stack.push(cur->right);
                    _stack.push(cur->right);
                }
                if(cur->left)
                {
                    _stack.push(cur->left);
                    _stack.push(cur->left);
                }
            }
            else
                result.push_back(cur->val);
        }
        return result;
        
    }
};

奇技淫巧:
和前序遍历的非递归解法类似,只不过是先把左结点压栈,再把右结点压栈,最后的结果取倒序就是后序遍历的结果,经过测试这样的流程是正确的,但是这不是真正的后序遍历。
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]
        """
        #后序遍历的非递归解法,奇技淫巧版
        stack=[]
        result=[]
        if not root:
            return result
        stack.append(root)
        while stack:
            tmp=stack.pop()
            result.append(tmp.val)
            if tmp.left:
                stack.append(tmp.left)
            if tmp.right:
                stack.append(tmp.right)
        return result[::-1] 

c++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<stack>
using namespace std;
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        //后序遍历非递归解法奇技淫巧版
        stack<TreeNode*>_stack;
        vector<int> result;
        if (!root)
            return result;
        _stack.push(root);
        while (!_stack.empty())
        {
            TreeNode*tmp =_stack.top();
            _stack.pop();
            result.push_back(tmp->val);
            if (tmp->left)
                _stack.push(tmp->left);
            if(tmp->right)
                _stack.push(tmp->right);
        }
        reverse(result.begin(),result.end());
        return result;
    }
};

总结:
二叉树的dfs的非递归解法中,后序遍历是最难的,但是有一种奇技淫巧法,和前序遍历的非递归解法类似,只是先把左子树入栈,再把右子树入栈,最后的结果倒序就是最终答案。
哪有什么所谓的经典解法,只要最终能得到正确答案的算法都是好算法~!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值