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 };
 
 
posted @ 2021-02-09 11:41  喵喵队立大功  阅读(70)  评论(0编辑  收藏  举报