Skip to content

Commit 31ec7aa

Browse files
committed
fd
1 parent 4ce3026 commit 31ec7aa

File tree

3 files changed

+32
-9
lines changed

3 files changed

+32
-9
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,7 @@
379379
|547|[Friend Circles](https://leetcode.com/problems/friend-circles/)|[Java](leetcode/solution/src/FriendCircles.java)|70||
380380
|557|[Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/)| [Java](leetcode/solution/src/ReverseWordsInAStringIII.java)|100||
381381
|560|[Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/)| [Java](leetcode/solution/src/SubarraySumEqualsK.java)|70||
382+
|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/)|[Java](leetcode/solution/src/BinaryTreeTilt.java)|90||
382383
|564|[Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/)|[Java](leetcode/solution/src/FindTheClosestPalindrome.java)|80|此题暴力法即可|
383384
|572|[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)|[Java](leetcode/solution/src/SubtreeOfAnotherTree.java)|80||
384385
|606|[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)|[Java](leetcode/solution/src/ConstructStringFromBinaryTree.java)|90||
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public class BinaryTreeTilt {
2+
3+
int tilt = 0;
4+
5+
public int findTilt(TreeNode root) {
6+
helper(root);
7+
return tilt;
8+
}
9+
10+
private int helper(TreeNode root) {
11+
if (root == null) {
12+
return 0;
13+
}
14+
int left = helper(root.left);
15+
int right = helper(root.right);
16+
tilt += Math.abs(left - right);
17+
return left + right + root.val;
18+
}
19+
}

leetcode/src/Main.java

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,21 @@ public class Main {
66

77
public static class Solution {
88

9-
public boolean isSubtree(TreeNode s, TreeNode t) {
10-
return isEqual(s, t) || (s != null && (isSubtree(s.left, t) || isSubtree(s.right, t)));
9+
int tilt = 0;
10+
11+
public int findTilt(TreeNode root) {
12+
helper(root);
13+
return tilt;
1114
}
1215

13-
private boolean isEqual(TreeNode s, TreeNode t) {
14-
if (t == null && s == null) {
15-
return true;
16-
}
17-
if (t == null || s == null) {
18-
return false;
16+
private int helper(TreeNode root) {
17+
if (root == null) {
18+
return 0;
1919
}
20-
return s.val == t.val && isEqual(s.left, t.left) && isEqual(s.right, t.right);
20+
int left = helper(root.left);
21+
int right = helper(root.right);
22+
tilt += Math.abs(left - right);
23+
return left + right + root.val;
2124
}
2225
}
2326

0 commit comments

Comments
 (0)