leetcode 543 Diameter of Binary Tree
阿新 • • 發佈:2018-12-13
dia etc right 最大的 node diameter oot leetcode lee
實際上是找出某左右子樹深度和最大的結點。不一定是根結點!!!
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int ans; public int maxDepth(TreeNode root) { if(root == null) return 0; int left = maxDepth(root.left); int right = maxDepth(root.right); ans = Math.max(ans, left+right); return Math.max(left, right)+1; } public int diameterOfBinaryTree(TreeNode root) { if(root == null) return 0; ans = 0; maxDepth(root); return ans; } }
leetcode 543 Diameter of Binary Tree