zoukankan      html  css  js  c++  java
  • Binary Tree Level Order Traversal&&II

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

    [
      [3],
      [9,20],
      [15,7]
    ]
    class Solution {
    public:
        vector > res;
    public:
        void trval(TreeNode *root,int level)
        {
            if(root==NULL)
                return;
           if(level==res.size())   //这句是关键啊
           {
               vector v;
               res.push_back(v);
           }
           res[level].push_back(root->val);
           trval(root->left,level+1);
           trval(root->right,level+1);
        }
        vector > levelOrder(TreeNode *root) {
            
            trval(root,0);
            return res;
          
            
        }
    };

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

    [
      [15,7],
      [9,20],
      [3]
    ]
    /**
     * 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<vector<int> > res;
        void order(TreeNode *root,int level)
        {
            if(root==NULL)
                return ;
           
            if(res.size()==level)
            {
                 vector<int> tmp;
                 res.push_back(tmp);
            }
                
            res[level].push_back(root->val);
            order(root->left,level+1);
            order(root->right,level+1);
        }
        vector<vector<int> > levelOrderBottom(TreeNode *root) {
            order(root,0);
            return vector<vector<int> > (res.rbegin(),res.rend());    //直接一句话解决了
            
            
        }
    };
  • 相关阅读:
    MYSQL中数据类型介绍
    怎么评估软件上线标准
    文件安全复制之 FastCopy
    强烈推荐美文之《从此刻起,我要》
    浅谈软件测试与墨菲定律
    夜神模拟器--安卓模拟神器
    RoadMap:如何创建产品路线图
    利用Python爬虫刷店铺微博等访问量最简单有效教程
    MySQL 数据库中删除重复数据的方法
    如何测试一个杯子
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4509910.html
Copyright © 2011-2022 走看看