码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode dfs Binary Tree Postorder Traversal

时间:2014-09-05 16:09:01      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   color   os   io   ar   for   div   

Binary Tree Postorder Traversal

 Total Accepted: 28560 Total Submissions: 92333My Submissions

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 iterativel



题意:后序遍历,不过给出了函数声明,限制了实现方式
思路:采用递归实现。因为函数声明是返回一个vector<int>,所以每个子树返回的是该子树的后序遍历的结果
按照 左、右、根的次序把根和左右子树的vector合并起来就可以了
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:


    vector<int> postorderTraversal(TreeNode *root) {
    vector<int> post;
    if(root == NULL) return post;
    TreeNode *left = root->left;
    TreeNode *right = root->right;
    
    if(left) {
    vector<int> left_vector = postorderTraversal(left);
    post.insert(post.end(), left_vector.begin(), left_vector.end());
    }
    if(right){
    vector<int> right_vector = postorderTraversal(right);
    post.insert(post.end(), right_vector.begin(), right_vector.end());
    }
    post.push_back(root->val);
    
    return post;
    }
};

Leetcode dfs Binary Tree Postorder Traversal

标签:des   style   http   color   os   io   ar   for   div   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/39081987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!