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].

思路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) {}
 * };
 */
class Solution {
private:
    vector<int> ivec;
    void postorder(TreeNode* root){
        if(root == NULL)
            return;
        postorder(root->left);
        postorder(root->right);
        ivec.push_back(root->val);
    }
public:
    vector<int> postorderTraversal(TreeNode* root) {
        ivec.clear();
        postorder(root);
        return ivec;
    }
};

你可能感兴趣的:(leetcode题解)