Skip to content

Commit 2ae4a0f

Browse files
committed
better solution for lc513
1 parent 86a3378 commit 2ae4a0f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Tree.md

+25
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ No.|Title|Difficulty|Solved|Date
1212
222|[Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)|Medium|yes|2019-01-04
1313
257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)|Easy|yes|2019-01-12
1414
297|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)|Hard|yes|2019-01-05
15+
513|[Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/)|Medium|yes|2019-01-14
1516
543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)|Easy|yes|2019-01-05
1617
589|[N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/)|Easy|yes|2019-01-05
1718
590|[N-ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal/)|Easy|yes|2019-01-05
@@ -80,6 +81,30 @@ No.|Title|Difficulty|Solved|Date
8081

8182
使用中序遍历来序列化二叉树。在进行反序列化二叉树的时候,使用递归的方式来进行。处理的第一个节点总是中间节点.
8283

84+
513. [Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/)
85+
86+
简单的,当然可以通过层次遍历来解决。
87+
88+
相对而言,更优美的方案是,递归的进行二叉树高度的比较。如果左右子树高度相当,则取左子树继续处理。最后处理到的节点,即是结果节点。
89+
90+
```java
91+
public int findBottomLeftValue(TreeNode root) {
92+
if (root.left == null && root.right == null) return root.val;
93+
int l = maxDepth(root.left);
94+
int r = maxDepth(root.right);
95+
if (l >= r) {
96+
return findBottomLeftValue(root.left);
97+
} else {
98+
return findBottomLeftValue(root.right);
99+
}
100+
}
101+
102+
private int maxDepth(TreeNode node) {
103+
if (node == null) return 0;
104+
return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
105+
}
106+
```
107+
83108
543. [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)
84109

85110
对于特定的某个节点,最大的长度为左子树的高度+右子树的高度。然后进行递归的求解。

src/main/java/medium/lc513.java

+16
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,20 @@ public int findBottomLeftValue(TreeNode root) {
4242
}
4343
return val;
4444
}
45+
46+
public int findBottomLeftValue2(TreeNode root) {
47+
if (root.left == null && root.right == null) return root.val;
48+
int l = maxDepth(root.left);
49+
int r = maxDepth(root.right);
50+
if (l >= r) {
51+
return findBottomLeftValue(root.left);
52+
} else {
53+
return findBottomLeftValue(root.right);
54+
}
55+
}
56+
57+
private int maxDepth(TreeNode node) {
58+
if (node == null) return 0;
59+
return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
60+
}
4561
}

0 commit comments

Comments
 (0)