题目

二叉树的直径,即是求树中任意俩点间的最大距离(深度)

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

The length of a path between two nodes is represented by the number of edges between them.

 

Example 1:

Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

Input: root = [1,2]
Output: 1

 

分析

- dfs深度优先,左右分别遍历

- 从子节点依次返回本层的最大,算出上级节点最大 max(left,right)

- 比较left+right与cur ans,更大,更新cur ans

- 如所在节点已是最下层,左右均无节点,返回时0+1=1,(本身有1的深度)max(left,right)+1

 

 

代码

***注意,int[] ans=new int[1] ;return ans[0] 如果要直接写为int ans

则ans需要为全局变量,否则无法更新不变

class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        int[] ans=new int[1];
        dfs(root,ans);
        return ans[0];
    }

    public int dfs(TreeNode root,int[] ans){
      if (root==null)
          return 0;//到头了没有孩子,以下的高度为0,跳出dfs
      int l_len=dfs(root.left,ans);
      int r_len=dfs(root.right,ans);
      ans[0]=Math.max(ans[0],l_len+r_len);
      return Math.max(l_len,r_len)+1;
    }
}

 

 posted on 2021-11-23 04:24  alau  阅读(20)  评论(0编辑  收藏  举报