File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode(int x) { val = x; }
8
+ * }
9
+ */
10
+
11
+ // 找从左到每个node的最长距离 和 从右到每个node的最长距离
12
+ public class Solution {
13
+ public int diameterOfBinaryTree(TreeNode root) {
14
+ if(root == null){
15
+ return 0;
16
+ }
17
+ int maxAns = 0;
18
+ // traverse every node
19
+ Stack<TreeNode> stack = new Stack<TreeNode>();
20
+ stack.push(root);
21
+ while (!stack.empty()) {
22
+ TreeNode node = stack.pop();
23
+ int temp = maxDepth(node.left) + maxDepth(node.right);
24
+ maxAns = maxAns > temp? maxAns: temp;
25
+ if (node.right != null) {
26
+ stack.push(node.right);
27
+ }
28
+ if (node.left != null) {
29
+ stack.push(node.left);
30
+ }
31
+ }
32
+ return maxAns;
33
+ }
34
+
35
+ public int maxDepth(TreeNode root){
36
+ if(root == null){
37
+ return 0;
38
+ }
39
+ return Math.max(maxDepth(root.left), maxDepth(root.right) ) + 1;
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments