二叉树查找主要有三种:前序查找、中序查找、后序查找
三种查找的思路分析:
- 先判断当前的结点node是否等于要查找的
- 如果是相等,则返回当前结点
- 如果不相等,则判断当前结点的左子结点是否为空,如果不为空,则递归前序查找
- 如果左递归前序查找,找到结点,则返回,否则继续判断,当前结点的右子结点是否为空,如果不空,则继续向右递归前序查找,如果找到则返回,否则没有找到。
- 判断当前结点的左子结点是否为空,如果不为空,则递归中序查找
- 如果找到则返回,如果没有找到,就和当前结点比较,如果是则返回当前结点,否则继续进行右递归中序查找
- 如果右递归中序查找找到则返回,否则返回nul
- 判断当前结点的左子结点是否为空,如果不为空,则递归后序查找
- 如果找到则返回,如果没有找到,就判断当前结点的右子结点是否为空,如果不为空,则右递归后序查找,如果找到就返回,如果没有找到
- 就和当前结点进行比较,如果找到则返回,否则返回nul
前序遍历代码实现
1. public class PostSearch {
2. /**
3. * @param root 二叉树的根节点
4. * @param id 要查找的id
5. * @return 查找到则返回对应id的Boy节点信息,没有查找则返回null
6. */
7. public static Boy postSearch(Boy root, char id) {
8. Boy temp = null;
9. if (root.getId() == id) {//一开始就判断root节点是否为要查找的节点
10. return root;
11. }
12. //判断当前结点的左子节点是否为空,如果不为空,则递归前序查找
13. if (root.getLeft() != null) {
14. temp = postSearch(root.getLeft(), id);
15. }
16. //2.如果左递归前序查找,找到结点,则返回
17. if (temp != null) {//说明我们左子树找到
18. return temp;
19. }
20. //若以上temp为null,则继续判断:
21. //当前的结点的右子节点是否为空,如果不空,则继续向右递归前序查找
22. if (root.getRight() != null) {
23. temp = postSearch(root.getRight(), id);
24. }
25. return temp;
26. }
27. }
中序遍历代码实现
1. public class InfixSearch {
2. public static Boy infixSearch(Boy boy, char id) {
3. Boy temp = null;
4. if (boy.getLeft() != null) {
5. temp = infixSearch(boy.getLeft(), id);
6. }
7. if (temp != null) {
8. return temp;
9. }
10. if (boy.getId() == id) {
11. return boy;
12. }
13. if (boy.getRight() != null) {
14. temp = infixSearch(boy.getRight(), id);
15. }
16. return temp;
17. }
18. }
后序遍历代码实现
1. public class LastSearch {
2. public static Boy lastSearch(Boy root, char id) {
3. Boy temp = null;
4. if (root.getLeft() != null) {
5. temp = lastSearch(root.getLeft(), id);
6. }
7. if (temp != null) {
8. return temp;
9. }
10. if (root.getRight() != null) {
11. temp = lastSearch(root.getRight(), id);
12. }
13. if (temp != null) {
14. return temp;
15. }
16. if (root.getId() == id) {
17. return root;
18. }
19. return temp;
20.
21. }
22. }