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. }
原文:https://www.cnblogs.com/bairentianshi/p/13920590.html