543. 二叉树的直径

 

 使用DFS求解

时间O(n),空间O(h)(h为整棵树的深度)

 1 class Solution {
 2     int res=0;
 3     public int diameterOfBinaryTree(TreeNode root) {
 4         def(root);
 5         return res;
 6     }
 7 
 8     public int def(TreeNode root){
 9         if(root==null) return 0;
10         int left=def(root.left);
11         int right=def(root.right);
12         // 计算左右子树高度和,本题要求路径和,刚好不需要额外处理
13         res = Math.max(left+right,res);
14         // 计算本子树的高度
15         return Math.max(left,right)+1;
16     }
17 }

 

posted @ 2021-05-05 17:07  jchen104  阅读(25)  评论(0编辑  收藏  举报