543. Diameter of Binary Tree

 1 //可以任意节点开始left+right 所以dfs的时候要每个节点都计算一下
 2 class Solution {
 3     int max = Integer.MIN_VALUE;
 4     public int diameterOfBinaryTree(TreeNode root) {
 5         if(root == null) return 0;
 6         dfs(root);
 7         return max;
 8     }
 9     
10     public int dfs(TreeNode root){
11         if(root == null) return 0;
12         int left = dfs(root.left);
13         int right = dfs(root.right);
14         int maxNow = left + right;
15         max = Math.max(maxNow, max);
16         return Math.max(right, left) + 1;
17     }
18 }

 

posted @ 2018-10-24 04:36  jasoncool1  阅读(85)  评论(0编辑  收藏  举报