-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSolution.java
94 lines (86 loc) · 2.3 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package ds.bst.leetcode700;
/**
* 二叉搜索树中的搜索
* LeetCode 700 https://leetcode-cn.com/problems/search-in-a-binary-search-tree/
*
* @author yangyi 2020年12月03日00:50:09
*/
public class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
/**
* 4
* / \
* 2 7
* / \
* 1 3
*/
private TreeNode createTree() {
TreeNode node_4 = new TreeNode(4);
TreeNode node_2 = new TreeNode(2);
TreeNode node_7 = new TreeNode(7);
TreeNode node_1 = new TreeNode(1);
TreeNode node_3 = new TreeNode(3);
node_4.left = node_2;
node_4.right = node_7;
node_2.left = node_1;
node_2.right = node_3;
return node_4;
}
private void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
/**
* 递归方式实现
*/
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) {
return null;
}
if (val > root.val) {
return searchBST(root.right, val);
} else if (val < root.val) {
return searchBST(root.left, val);
} else {
return root;
}
}
/**
* 迭代方式实现
*/
public TreeNode searchBST2(TreeNode root, int val) {
while (root != null) {
if (val < root.val) {
root = root.left;
} else if (val > root.val) {
root = root.right;
} else {
return root;
}
}
return null;
}
public static void main(String[] args) {
Solution bstSearch = new Solution();
System.out.println("创建一颗BST: ");
TreeNode root = bstSearch.createTree();
System.out.println("中序遍历构建好的BST: ");
bstSearch.inOrder(root);
System.out.println();
System.out.println("查找对应以2为根的子树---");
TreeNode result = bstSearch.searchBST(root, 2);
System.out.println("中序遍历查找返回的结果: ");
bstSearch.inOrder(result);
}
}