首页 > 其他 > 详细

LeetCode 中级 -二叉树的层次遍历(102)

时间:2019-04-20 17:51:54      阅读:160      评论:0      收藏:0      [点我收藏+]

题目描述:
    

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

思路:
    笔试时采用了queue的遍历方式,但用的是一维数组存的,感觉有点别扭。
    网上的queue解法模板
    
/**
 * 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<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;//保存结果
        TreeNode * first =root;
        if(!first)
            return res;
        queue<TreeNode *> q;
        q.push(first);
        while(!q.empty())
        {
            int count = q.size();
            vector<int> t;
            while(count!=0)
            {
                TreeNode *p=q.front();
                q.pop();
                t.push_back(p->val);
                if(p->left)
                    q.push(p->left);
                if(p->right)
                    q.push(p->right);
                count--;
            }
            res.push_back(t);
        }
        return res;
    }
};

第二种采用先序遍历递归,个人感觉代码更加简洁,但稍微难理解点。复杂度都是O(n)

  • 利用depth变量记录当前在第几层(从0开始),进入下层时depth + 1
  • 如果depth >= vector.size()说明这一层还没来过,这是第一次来,所以得扩容咯;
  • 因为是前序遍历,中-左-右,对于每一层来说,左边的肯定比右边先被遍历到,实际上后序中序都是一样的。。。
/**
 * 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:
    
    void pre(TreeNode *root,int depth, vector<vector<int>> &res)
    {
        if(root==NULL)
            return ;
        if(depth>=res.size())
            res.push_back(vector<int>{});
        res[depth].push_back(root->val);
        pre(root->left,depth+1,res);
        pre(root->right,depth+1,res);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> ans;
            pre(root,0,ans);
            return ans;
    }
};

 

LeetCode 中级 -二叉树的层次遍历(102)

原文:https://www.cnblogs.com/-xinxin/p/10741800.html

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