zoukankan      html  css  js  c++  java
  • leetcode 102. 二叉树的层序遍历

    地址   https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

    给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
    
     
    
    示例:
    二叉树:[3,9,20,null,null,15,7],
    
        3
       / 
      9  20
        /  
       15   7
    返回其层次遍历结果:
    
    [
      [3],
      [9,20],
      [15,7]
    ]

    解答

    遍历树的时候 加上层级计数。 根据层级将指针的值加入到不同的vector中

    /**
     * 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>> vv;
        
        void printVector(TreeNode* root,int level)
        {
            if(root == NULL) return;
            if(vv.size() < level+1){
                vector<int> v{root->val};
                vv.push_back(v);
            }else if(vv.size() >= level+1){
                vv[level].push_back(root->val);
            }     
            
            printVector(root->left,level+1);
            printVector(root->right,level+1);
        }
        
        vector<vector<int>> levelOrder(TreeNode* root) {
            printVector(root,0);    
            
            return vv;
        }
    };

    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    Windows系统下静态库和动态库的生成方法
    c语言 9-9
    c语言中统计字符串中数字字符出现的次数
    c语言 9-8
    c语言 9-7
    c语言中使用putchar显示字符串
    c语言 9-6
    c语言 9-5
    c语言 9-4
    c语言中输出字符串的长度
  • 原文地址:https://www.cnblogs.com/itdef/p/12884929.html
Copyright © 2011-2022 走看看