Monday, November 10, 2014

[LeetCode] 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].
Note: Recursive solution is trivial, could you do it iteratively?

1. 递归解法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> allNodeValues;
        postorderTrav(root, allNodeValues);
        return allNodeValues;
    }
    
    void postorderTrav(TreeNode *root, vector<int> &allNodeValues) {
        if(!root) return;
        postorderTrav(root->left, allNodeValues);
        postorderTrav(root->right, allNodeValues);
        allNodeValues.push_back(root->val);
    }
};

2. 迭代解法:


No comments:

Post a Comment