package org.learn.datastructures.tree.binary;
public class BinaryTree {
/**
* @param args
*/
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
Node rootNode = new Node(10);
tree.insert(rootNode, 20);
tree.insert(rootNode, 30);
tree.insert(rootNode, 5);
tree.insert(rootNode, 6);
tree.insert(rootNode, 16);
tree.insert(rootNode, 67);
tree.insert(rootNode, 116);
tree.search(rootNode);
}
public void insert(Node node, int data) {
if (node.data < data) {
if (node.left != null)
insert(node.left, data);
else
node.left = new Node(data);
} else if (node.data > data) {
if (node.right != null)
insert(node.right, data);
else
node.right = new Node(data);
}
}
public void search(Node node) {
if (node == null)
return;
search(node.right);
System.out.println(node.data);
search(node.left);
}
}
class Node {
Node left;
Node right;
int data;
public Node(int data) {
this.data = data;
}
}
public class BinaryTree {
/**
* @param args
*/
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
Node rootNode = new Node(10);
tree.insert(rootNode, 20);
tree.insert(rootNode, 30);
tree.insert(rootNode, 5);
tree.insert(rootNode, 6);
tree.insert(rootNode, 16);
tree.insert(rootNode, 67);
tree.insert(rootNode, 116);
tree.search(rootNode);
}
public void insert(Node node, int data) {
if (node.data < data) {
if (node.left != null)
insert(node.left, data);
else
node.left = new Node(data);
} else if (node.data > data) {
if (node.right != null)
insert(node.right, data);
else
node.right = new Node(data);
}
}
public void search(Node node) {
if (node == null)
return;
search(node.right);
System.out.println(node.data);
search(node.left);
}
}
class Node {
Node left;
Node right;
int data;
public Node(int data) {
this.data = data;
}
}
No comments:
Post a Comment