|
3 | 3 | import com.fishercoder.common.classes.TreeNode;
|
4 | 4 |
|
5 | 5 | /**
|
6 |
| - * Given a binary tree, you need to compute 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. |
| 6 | + * 543. Diameter of Binary Tree |
| 7 | + * |
| 8 | + * Given a binary tree, you need to compute the length of the diameter of the tree. |
| 9 | + * The diameter of a binary tree is the length of the longest path between any two nodes in a tree. |
| 10 | + * This path may or may not pass through the root. |
7 | 11 |
|
8 | 12 | Example:
|
9 | 13 | Given a binary tree
|
|
18 | 22 | */
|
19 | 23 | public class _543 {
|
20 | 24 |
|
21 |
| - int diameter = 0; |
22 |
| - |
23 |
| - public int diameterOfBinaryTree(TreeNode root) { |
24 |
| - dfs(root); |
25 |
| - return diameter; |
26 |
| - } |
| 25 | + public static class Solution1 { |
| 26 | + /**This is a very great problem for practicing recursion: |
| 27 | + * 1. What dfs() returns is the max height it should pick from either its left or right subtree, that's |
| 28 | + * what the int return type stands for; |
| 29 | + * 2. And during the recursion, we can keep updating the global variable: "diameter"; |
| 30 | + * 3. When computing length/height of a subtree, we should take the max of its left and right, then plus one |
| 31 | + * and left height should be like this |
| 32 | + * int left = dfs(root.left); |
| 33 | + * instead of dfs(root.left) + 1; |
| 34 | + * we'll only plus one at the end |
| 35 | + * */ |
| 36 | + int diameter = 0; |
| 37 | + |
| 38 | + public int diameterOfBinaryTree(TreeNode root) { |
| 39 | + dfs(root); |
| 40 | + return diameter; |
| 41 | + } |
27 | 42 |
|
28 |
| - private int dfs(TreeNode root) { |
29 |
| - if (root == null) { |
30 |
| - return 0; |
| 43 | + private int dfs(TreeNode root) { |
| 44 | + if (root == null) { |
| 45 | + return 0; |
| 46 | + } |
| 47 | + int left = dfs(root.left); |
| 48 | + int right = dfs(root.right); |
| 49 | + diameter = Math.max(diameter, left + right); |
| 50 | + return Math.max(left, right) + 1; |
31 | 51 | }
|
32 |
| - int left = dfs(root.left); |
33 |
| - int right = dfs(root.right); |
34 |
| - diameter = Math.max(diameter, left + right); |
35 |
| - return Math.max(left, right) + 1; |
36 | 52 | }
|
37 |
| - |
38 | 53 | }
|
0 commit comments