下面是一个二叉树,查找某个值是否存在。
代码:
public class TestTree {
static class Node {
public char val;
public Node left;
public Node right;
public Node(char val) {
this.val = val;
// 以下两个代码可以省略.
// 引用类型的成员变量, 会被默认初始化为 null
this.left = null;
this.right = null;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
'}';
}
}
// 辅助我们构造测试数据的.
static Node build() {
// 通过 build 方法构建一棵树, 返回树的根节点
Node A = new Node('A');
Node B = new Node('B');
Node C = new Node('C');
Node D = new Node('D');
Node E = new Node('E');
Node F = new Node('F');
Node G = new Node('G');
A.left = B;
A.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
return A;
}
public static Node Find(Node root,char toFind) {
if(root==null) {
return null;
}
if(root.val==toFind) {
return root;
}
Node result= Find(root.left,toFind);
if(result!=null) {
return result;
}
return Find(root.right,toFind);
}
public static void main(String[] args) {
Node root = build();
System.out.println(Find(root, 'G'));
}
}
**运行结果:**