1. 程式人生 > >145. Binary Tree Postorder Traversal(python+cpp)

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

總結: