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

Binary Tree Preorder Traversal and Binary Tree Postorder Traversal

时间:2014-10-19 22:42:10      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   os   ar   for   sp   

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

 

return [1,2,3].

 

c++版:

/**
 * 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> preorderTraversal(TreeNode *root) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        vector<int> result;  
        vector<int> left;  
        vector<int> right;  
          
        if(root == NULL) return result;  
        result.push_back(root->val);  
        left = preorderTraversal(root->left);  
        right = preorderTraversal(root->right);  
          
        if(left.size() != 0)  
            result.insert(result.end(), left.begin(), left.end());  
        if(right.size() != 0)  
            result.insert(result.end(), right.begin(), right.end());  
          
        return result;  
          
    }  
};

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

C++版本:

/**
 * 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> ret;  
        dfs(root, ret);  
        return ret;  
    }  
  
    void dfs(TreeNode* root, vector<int>& ret)  
    {  
        if(NULL == root)  
            return ;  
        dfs(root->left, ret);  
        dfs(root->right, ret);  
        ret.push_back(root->val); 
    }     
    
};

  

Binary Tree Preorder Traversal and Binary Tree Postorder Traversal

标签:des   style   blog   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/zlz-ling/p/4035509.html

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