Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4634824

Browse files
add a solution for 285
1 parenta263631 commit4634824

File tree

1 file changed

+30
-1
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+30
-1
lines changed

‎src/main/java/com/fishercoder/solutions/_285.java

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
importcom.fishercoder.common.classes.TreeNode;
44

5+
importjava.util.ArrayList;
56
importjava.util.Iterator;
7+
importjava.util.List;
68
importjava.util.Map;
79
importjava.util.TreeMap;
810

@@ -17,7 +19,7 @@ public static class Solution1 {
1719
* <p>
1820
* The time complexity should be O(h) where h is the depth of the result node.
1921
* succ is a pointer that keeps the possible successor.
20-
* Whenever you go left the current root is the new possible successor, otherwisetheit remains the same.
22+
* Whenever you go left the current root is the new possible successor, otherwise it remains the same.
2123
* <p>
2224
* Only in a balanced BST O(h) = O(log n). In the worst case h can be as large as n.
2325
*/
@@ -64,4 +66,31 @@ private void inorderTraversal(TreeNode root, TreeMap<Integer, TreeNode> map) {
6466
}
6567
}
6668

69+
publicstaticclassSolution3 {
70+
publicTreeNodeinorderSuccessor(TreeNoderoot,TreeNodep) {
71+
List<TreeNode>inorder =newArrayList<>();
72+
dfs(root,inorder);
73+
for (inti =0;i <inorder.size() -1;i++) {
74+
if (inorder.get(i) ==p) {
75+
returninorder.get(i +1);
76+
}
77+
}
78+
returnnull;
79+
}
80+
81+
privateList<TreeNode>dfs(TreeNoderoot,List<TreeNode>inorder) {
82+
if (root ==null) {
83+
returninorder;
84+
}
85+
if (root.left !=null) {
86+
dfs(root.left,inorder);
87+
}
88+
inorder.add(root);
89+
if (root.right !=null) {
90+
dfs(root.right,inorder);
91+
}
92+
returninorder;
93+
}
94+
}
95+
6796
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp