首页 > 其他 > 详细

Leetcode[145]-Binary Tree Postorder Traversal

时间:2015-06-13 11:22:29      阅读:178      评论:0      收藏:0      [点我收藏+]

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

Leetcode[145]-Binary Tree Postorder Traversal

原文:http://blog.csdn.net/dream_angel_z/article/details/46480869

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!