zoukankan      html  css  js  c++  java
  • LeetCode 107. 二叉树的层次遍历 II DFS

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

    给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
    
    例如:
    给定二叉树 [3,9,20,null,null,15,7],
    
        3
       / 
      9  20
        /  
       15   7
    返回其自底向上的层次遍历为:
    
    [
      [15,7],
      [9,20],
      [3]
    ]

    算法1
    dfs 要加入遍历到的层次

    C++ 代码

    /**
     * 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>> ans;
        void dfs(TreeNode* root,int level){
            if(root==NULL) return;
    
            if(level > ans.size()){
                vector<int> v;v.push_back(root->val);
                ans.push_back(v);
            }else{
                ans[level-1].push_back(root->val);
            }
    
            dfs(root->left,level+1);
            dfs(root->right,level+1);
    
        }
    
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            dfs(root,1);
            reverse(ans.begin(),ans.end());
            return ans;
        }
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    OSI 与 TCP/IP协议簇
    交换机工作原理
    Windows搭建域环境
    网络安全散装笔记
    Python之正则匹配——RE模块
    Django框架之ORM数据库操作
    Django中ORM的优化
    python遍历文件夹下文件
    numpy.r_ c_
    python调用google map api
  • 原文地址:https://www.cnblogs.com/itdef/p/13622658.html
Copyright © 2011-2022 走看看