zoukankan      html  css  js  c++  java
  • Binary Tree Preorder Traversal and Binary Tree Postorder Traversal

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

      

  • 相关阅读:
    P3916 图的遍历 题解
    NBL小可爱纪念赛「 第一弹 」 游记(部分题解)
    P4147 玉蟾宫 题解
    十、一些小例子
    九、基础正则表达式BRE
    八.linux系统文件属性知识
    七、linux目录结构知识---实战
    六、linux目录结构知识
    3.20-30岁形成好的习惯
    五、Centos linux系统优化-实战
  • 原文地址:https://www.cnblogs.com/zlz-ling/p/4035509.html
Copyright © 2011-2022 走看看