二叉树的三种遍历方法,及树结点的删除(java源代码)

  • 满二叉树和完全二叉树的区别
    /
    /

  • 前序遍历,中序遍历,后序遍历。是相对于父结点来说的
    /
    public class Main {
    public static void main(String[] args) {
    Node node1=new Node(1, “刘备”);
    Node node2=new Node(2, “关羽”);
    Node node3=new Node(3, “张飞”);
    Node node4=new Node(4, “赵云”);
    Node node5=new Node(5, “黄忠”);
    Node node6=new Node(6, “马超”);
    Tree tree=new Tree(node1);
    node1.left=node2;
    node1.right=node3;
    node3.left=node4;
    node3.right=node6;
    node4.right=node5;
    /

    System.out.println(“中序遍历的结果为:”);
    tree.preorder(node1);
    System.out.println(“中序遍历的结果为:”);
    tree.inorder(node1);
    System.out.println(“后序遍历的结果为:”);
    tree.postorder(node1);
    Node node=tree.preorderSearch(6, node1);//查找id为6发结点
    if(node==null) {
    System.out.println(“未找到该结点”);
    }else {
    System.out.println(“该结点为”+node.toString());
    }
    */
    tree.deleteNode(3, node1);
    }
    }
    //结点
    class Node{
    public int id;
    public String name;
    Node left;
    Node right;

    public Node(int id, String name) {
    super();
    this.id = id;
    this.name = name;
    }

    @Override
    public String toString() {
    return “Node [id=” + id + “, name=” + name + “]”;
    }
    }

class Tree{
public Node root;

public Tree(Node root) {
	super();
	this.root = root;
}
//前序序遍历。先父结点,然后左结点,然后右结点
public void preorder(Node root) {
	System.out.println(root.toString());
	if(root.left!=null) {
		preorder(root.left);
	}
	if(root.right!=null) {
		preorder(root.right);
	}
}
//中序遍历。先左节点,再父结点,再右结点
public void inorder(Node root) {
	if(root.left!=null) {
		inorder(root.left);
	}
	System.out.println(root.toString());
	if(root.right!=null) {
		inorder(root.right);
	}
}
//后序遍历。先左结点,再右结点,再父结点
public void postorder(Node root) {
	if(root.left!=null) {
		postorder(root.left);
	}
	if(root.right!=null) {
		postorder(root.right);
	}
	System.out.println(root.toString());
}
//前序遍历查找
public Node preorderSearch(int id,Node root) {
	if(root.id==id) {
		return root;
	}
	Node temp=null;
	if(root.left!=null) {
		temp=preorderSearch(id, root.left);
	}
	if(temp!=null) {
		return temp;
	}
	if(root.right!=null) {
		temp=preorderSearch(id, root.right);
	}
	return temp;	
}
public void deleteNode(int id,Node root) {
	if(root.id==id) {
		root=null;
		System.out.println("删除成功");
	}else {
		if(delete(id, root)) {
			System.out.println("删除成功");
		}else {
			System.out.println("该结点不存在");
		}
	}
	preorder(root);
}
public boolean delete(int id,Node root) {
	if(root.left!=null&&root.left.id==id) {
		root.left=null;
		return true;
	}
	if(root.right!=null&&root.right.id==id) {
		root.right=null;
		return true;
	}
	if(root.left!=null) {
		delete(id, root.left);
	}
	if(root.right!=null) {
		delete(id, root.right);
	}
	return false;
}

}

你可能感兴趣的:(二叉树的三种遍历方法,及树结点的删除(java源代码))