在树中搜索值
搜索给定树是否包含特定元素。如果找到,将其与树中的每个元素进行比较,并显示一条消息,说明已找到元素。
示例
class Node{ int data; Node leftNode, rightNode; Node() { leftNode = null; rightNode = null; this.data = data; } Node(int data) { leftNode = null; rightNode = null; this.data = data; } int getData() { return this.data; } Node getleftNode() { return this.leftNode; } Node getRightNode() { return this.leftNode; } void setData(int data) { this.data = data; } void setleftNode(Node leftNode) { this.leftNode = leftNode; } void setRightNode(Node rightNode) { this.leftNode = rightNode; } } public class SeachingValue { public static void main(String[] args) { Node node = new Node(50); node.leftNode = new Node(60); node.leftNode.leftNode = new Node(45); node.leftNode.rightNode = new Node(64); node.rightNode = new Node(60); node.rightNode.leftNode = new Node(45); node.rightNode.rightNode = new Node(64); System.out.println("Pre order of the above created tree :"); preOrder(node); System.out.println(); int data = 60; boolean b = find(node, data); if(b) { System.out.println("Element found"); } else { System.out.println("Element not found"); } } public static void preOrder(Node root) { if(root !=null) { System.out.print(root.data+" "); preOrder(root.leftNode); preOrder(root.rightNode); } } public static boolean find(Node root, int data) { if(root == null) { return false; } if(root.getData() == data) { return true; } return find(root.getleftNode(), data)||find(root.getRightNode(), data); } }
输出
Pre order of the above created tree : 50 60 45 64 60 45 64 Element found
广告