您的位置:首页 > 其它

Leetcode[145]-Binary Tree Postorder Traversal

2015-06-13 10:10 375 查看
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?

方法一:递归遍历

/**
 * 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> nums;
    vector<int> postorderTraversal(TreeNode* root) {
        postorder(root);
        return nums;
    }

    void postorder(TreeNode * root){
        if(root==NULL) return;
        if(root->left) postorder(root->left);
        if(root->right) postorder(root->right);
        nums.push_back(root->val);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: