package dataStructure;
import java.util.*;
public class BinaryTree {
public BinaryTree()
{
root = null;
}
public boolean search(int data)
{
TreeNode node = root;
while(node != null)
{
if(node.data == data)
return true;
else if(node.data < data)
node = node.rightChild;
else
node = node.leftChild;
}
return false;
}
//默认二叉搜索树中的所有元素都不相同。
public void insert(int data)
{
TreeNode newNode = new TreeNode(data);
if(root == null)
root = newNode;
else
{
TreeNode node = root;
while(node != null)
{
if(data < node.data)
if(node.leftChild == null)
{
node.leftChild = newNode;
break;
}
else
node = node.leftChild;
else
if(node.rightChild == null)
{
node.rightChild = newNode;
break;
}
else
node = node.rightChild;
}
}
}
public boolean delete(int data)
{
if(root == null)
return false;
else
{
TreeNode current = root;
TreeNode parent = root;
boolean isLeftChild = true;//current是parent的左孩子?
//寻找值为data的节点current。
while(current.data != data)
{
parent = current;
if(data < current.data)
{
current = current.leftChild;
isLeftChild = true;
}else
{
current = current.rightChild;
isLeftChild = false;
}
if(current == null)
return false;
}
TreeNode cur;//替换current节点。
if(current.leftChild != null && current.rightChild != null)
{
//寻找current前驱节点,并用它代替current。
TreeNode par = current.leftChild;
cur = current.leftChild;
while(cur.rightChild != null)
{
par = cur;
cur = cur.rightChild;
}
if(par != cur)//意味着待删除的current节点的左孩子有子节点。
{
par.rightChild = cur.leftChild;
cur.leftChild = current.leftChild;
}
cur.rightChild = current.rightChild;
}
else if(current.leftChild != null)//current右子树为空
cur = current.leftChild;
else//current左子树为空
cur = current.rightChild;
if(current == root)//删除的是根节点。
root = cur;
else
if(isLeftChild)
parent.leftChild = cur;
else
parent.rightChild = cur;
return true;
}
}
//遍历输出树节点。
public void output()
{
display(root);
}
public void output2()//未递归。
{
display2(root);
}
//中序遍历
private static void display(TreeNode node)
{
if(node != null)
{
display(node.leftChild);
System.out.print(node.data+" ");
display(node.rightChild);
}
}
private static void display2(TreeNode node)
{
if(node != null)
{
Stack stack = new Stack();
stack.push(node);
TreeNode current = node;
while(!stack.empty())
{
//若current的左孩子非空,则进栈。
while(current.leftChild != null)
{
current = current.leftChild;
stack.push(current);
}
System.out.print(((TreeNode)stack.pop()).data+" ");
//若current没有有孩子,则输出栈元素。
while(current.rightChild == null)
{
if(!stack.empty())
{
current = (TreeNode)stack.pop();
System.out.print(current.data+" ");
}else
break;
}
//有右孩子,右孩子进栈。
if(current.rightChild != null)
{
current = current.rightChild;
stack.push(current);
}
}
}
}
private TreeNode root;
}
class TreeNode
{
public TreeNode(int data)
{
this.data = data;
this.leftChild = null;
this.rightChild = null;
}
public int data;
public TreeNode leftChild;
public TreeNode rightChild;
}