zoukankan      html  css  js  c++  java
  • 104、二叉树的最大深度

    给定一个二叉树,找出其最大深度。

    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

    说明: 叶子节点是指没有子节点的节点。

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

          3
         / 
        9  20
          /  
         15   7

    返回它的最大深度 3 。

    题解:

    可以利用DFS递归调用,根结点不存在说明高度为0。C++11里nullptr代表空指针。

    /* C++ */

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10  * };
    11  */
    12 class Solution {
    13 public:
    14     int maxDepth(TreeNode* root) {
    15         if(root==nullptr) return 0;
    16         return max(maxDepth(root->left),maxDepth(root->right))+1;
    17     }
    18 };

    /* JavaScript */

    深度优先遍历

     1 /**
     2  * Definition for a binary tree node.
     3  * function TreeNode(val, left, right) {
     4  *     this.val = (val===undefined ? 0 : val)
     5  *     this.left = (left===undefined ? null : left)
     6  *     this.right = (right===undefined ? null : right)
     7  * }
     8  */
     9 /**
    10  * @param {TreeNode} root
    11  * @return {number}
    12  */
    13 var maxDepth = function(root) {
    14     let res = 0;
    15     const dfs = (n,l) => {  //l代表层级
    16         if(!n) {return;}
    17         if(!n.left && !n.right) {
    18             res = Math.max(res, l); //判断最大深度
    19         }
    20         dfs(n.left, l+1);
    21         dfs(n.right, l+1);
    22     }
    23     dfs(root,1);  
    24     return res;
    25 };
     1 /**
     2  * Definition for a binary tree node.
     3  * function TreeNode(val, left, right) {
     4  *     this.val = (val===undefined ? 0 : val)
     5  *     this.left = (left===undefined ? null : left)
     6  *     this.right = (right===undefined ? null : right)
     7  * }
     8  */
     9 /**
    10  * @param {TreeNode} root
    11  * @return {number}
    12  */
    13 var maxDepth = function(root) {
    14     if(!root) {
    15         return 0;
    16     }else{
    17         const left=maxDepth(root.left);
    18         const right=maxDepth(root.right);
    19         return Math.max(left,right)+1;
    20     }
    21 };
     
     
  • 相关阅读:
    移植Valgrind检测Android JNI内存泄漏
    【转】线性回归最小二乘法和梯度下降法
    【转】成为一名推荐系统工程师永远都不晚
    vue-element-admin使用常见问题
    SpringBoot中如何使用jpa和jpa的相关知识总结
    SpringBoot Controller接收参数的几种常用方式
    java项目其他基础配置
    eclipse 新建 maven 项目 + 消除错误
    vue城市三级联动组件 vue-area-linkage
    Vue中watch的简单应用
  • 原文地址:https://www.cnblogs.com/oaoa/p/14392402.html
Copyright © 2011-2022 走看看