二叉树查找编号为 n 的节点,我自己的写法,与网上略有不同
import java.util.Objects; public class Main { public static void main(String[] args) { //创建节点 Node rootNode = new Node(); rootNode.setData("唐僧"); rootNode.setNo(1); Node node1 = new Node(); node1.setData("孙悟空"); node1.setNo(2); Node node2 = new Node(); node2.setData("猪八戒"); node2.setNo(3); Node node3 = new Node(); node3.setData("沙和尚"); node3.setNo(4); Node node4 = new Node(); node4.setNo(5); node4.setData("白龙马"); //挂数据 rootNode.setLeftNode(node1); rootNode.setRightNode(node2); node2.setRightNode(node3); node2.setLeftNode(node4); //打印输出 BinaryTree tree = new BinaryTree(); System.out.println("前序遍历"); tree.preOrder(rootNode); // System.out.println("中序遍历"); // tree.middleOrder(rootNode); // System.out.println("后序遍历"); // tree.backOrder(rootNode); Node node = tree.findNode(4,rootNode); System.out.println("你要查找的节点为:"+node); } } class BinaryTree { //前序遍历 父的先后 public void preOrder(Node node) { System.out.println(node.toString()); if(Objects.nonNull(node.getLeftNode())) { preOrder(node.getLeftNode()); } if(Objects.nonNull(node.getRightNode())) { preOrder(node.getRightNode()); } } public void middleOrder(Node node) { if(Objects.nonNull(node.getLeftNode())) { middleOrder(node.getLeftNode()); } System.out.println(node.toString()); if(Objects.nonNull(node.getRightNode())) { middleOrder(node.getRightNode()); } } public void backOrder(Node node) { if(Objects.nonNull(node.getLeftNode())) { backOrder(node.getLeftNode()); } if(Objects.nonNull(node.getRightNode())) { backOrder(node.getRightNode()); } System.out.println(node.toString()); } //查找编号为n 的节点,核心代码 public Node findNode(int n,Node node) { if(node.getNo() == n) { return node; } if(Objects.nonNull(node.getLeftNode()) ) { Node tempNode = findNode(n,node.getLeftNode()); if(Objects.nonNull(tempNode) && tempNode.getNo() == n ) { return tempNode; } } if(Objects.nonNull(node.getRightNode()) ) { Node tempNode = findNode(n,node.getRightNode()); if(Objects.nonNull(tempNode) && tempNode.getNo() == n) { return tempNode; } } return null; } } //定义节点结构 class Node { private Node leftNode; private Node rightNode; private String data; private int no; public int getNo() { return no; } public void setNo(int no) { this.no = no; } public Node getLeftNode() { return leftNode; } public void setLeftNode(Node leftNode) { this.leftNode = leftNode; } public Node getRightNode() { return rightNode; } public void setRightNode(Node rightNode) { this.rightNode = rightNode; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public String toString() { return "Node{" + "data='" + data + '\'' + ", no=" + no + '}'; } }
本文来自博客园,作者:狂躁的键盘,转载请注明原文链接:https://www.cnblogs.com/wangweiip/p/16683174.html