Binary Tree Postorder Traversal(C++ LintCode)

解题思路:

(1)二叉树的后序序列

(2)递归时主要考虑的是出题人给的函数返回类型

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: Postorder in ArrayList which contains node values.
     */
    vector<int> postorderTraversal(TreeNode * root) {
        // write your code here
        if (root==NULL) {
            vector<int> temp;
            return temp;
        }
        vector<int> left = postorderTraversal(root->left);
        vector<int> right = postorderTraversal(root->right);
        
        vector<int> total;
        total.insert(total.end(),left.begin(),left.end());
        total.insert(total.end(),right.begin(),right.end());
        total.push_back(root->val);
        return total;
    }
};

发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105626750