码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 543. Diameter of Binary Tree

时间:2020-03-18 09:24:23      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:node   htm   ==   递归   idt   tco   距离   bsp   ble   

二叉树的直径。题意是给一个二叉树,找二叉树里面的最大直径。最大直径的定义是任意两个node之间的最大距离。例子,

Given a binary tree

          1
         /         2   3
       / \     
      4   5    

 

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

注意这个最大距离很有可能不经过根节点,如下图例子,最大直径是从9到8,摘自LC中文网

技术图片

思路是类似104题找二叉树最大深度用到的递归,但是稍微做一点改动。设置一个全局变量记录res这个最大长度,递归函数找的依然是最大深度但是res记录的是Math.max(res, left + right),即当前节点的左子树最大深度 + 右子树最大深度。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     int res = 0;
 3 
 4     public int diameterOfBinaryTree(TreeNode root) {
 5         helper(root);
 6         return res;
 7     }
 8 
 9     private int helper(TreeNode root) {
10         if (root == null) {
11             return 0;
12         }
13         int left = helper(root.left);
14         int right = helper(root.right);
15         res = Math.max(res, left + right);
16         return Math.max(left, right) + 1;
17     }
18 }

 

JavaScript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number}
 4  */
 5 var diameterOfBinaryTree = function (root) {
 6     let res = 0;
 7     var helper = function (root) {
 8         if (root == null) {
 9             return 0;
10         }
11         let left = helper(root.left);
12         let right = helper(root.right);
13         res = Math.max(res, left + right);
14         return Math.max(left, right) + 1;
15     };
16     helper(root);
17     return res;
18 };

 

[LeetCode] 543. Diameter of Binary Tree

标签:node   htm   ==   递归   idt   tco   距离   bsp   ble   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12515089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!