二叉树三种递归排序



public static void main(String[] args) {
BinaryTree<Character> binaryTree = new BinaryTree<Character>();


// 输入ABDH##I##E##CF#J##G##(#用null代替)
LinkedList<Character> tree = new LinkedList<Character>();
tree.add('A');
tree.add('B');
tree.add('D');
tree.add('H');
tree.add(null);
tree.add(null);
tree.add('I');
tree.add(null);
tree.add(null);
tree.add('E');
tree.add(null);
tree.add(null);
tree.add('C');
tree.add('F');
tree.add(null);
tree.add('J');
tree.add(null);
tree.add(null);
tree.add('G');
tree.add(null);
tree.add(null);
TreeNode<Character> root = binaryTree.creatBinaryPre(tree);
// 先序遍历(递归)
binaryTree.PrintBinaryTreePreRecur(root);
System.out.println();
// 中序遍历(递归)
binaryTree.PrintBinaryTreeMidRecur(root);
System.out.println();
// 后序遍历(递归)
binaryTree.PrintBinaryTreeBacRecur(root);
System.out.println();
// 先序遍历(非递归)
binaryTree.PrintBinaryTreePreUnRecur(root);
System.out.println();
// 中序遍历(非递归)
binaryTree.PrintBinaryTreeMidUnrecur(root);
System.out.println();
// 后序遍历(非递归)
binaryTree.PrintBinaryTreeBacUnrecur(root);
System.out.println();
// 层次遍历(非递归)


}


// 先序遍历,返回根节点
public TreeNode createBinaryPre(LinkedList<T> treeData) {
TreeNode root = null;
T data = treeData.removeFirst();
if (data != null) {
root = new TreeNode<T>(data, null, null);
root.left = creatBinaryPre(treeData);
root.right = creatBinaryPre(treeData);
}
return root;
}


public void PrintBinaryTreePreRecur(TreeNode<T> root) {


if (root != null) {
System.out.println(root.data);
PrintBinaryTreePreRecur(root.left);
PrintBinaryTreePreRecur(root.right);
}


}


@SuppressWarnings("unchecked")
public void PrintBinaryTreePreUnRecur(TreeNode<T> root) {
TreeNode<T> p = root;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
while (p != null && !stack.isEmpty()) {
if (p != null) {
stack.push(p);
System.out.println(p.data);
p = p.left;
} else {
p = stack.pop();
p = p.right;
}
}
}


public void PrintBinaryTreeMidRecur(TreeNode<T> root) {
if (root != null) {
PrintBinaryTreeMidRecur(root.left);
System.out.println(root.data);
PrintBinaryTreeMidRecur(root.right);
}
}


public void PrintBinaryTreeMidUnrecur(TreeNode<T> root) {
TreeNode<T> p = root;// p为当前节点
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
// 栈不为空时,或者p不为空时循环
while (p != null || !stack.isEmpty()) {
// 当前节点不为空。压入栈中。并将当前节点赋值为左儿子
if (p != null) {
stack.push(p);
p = p.left;
}
// 当前节点为空:
// 1、当p指向的左儿子时,此时栈顶元素必然是它的父节点
// 2、当p指向的右儿子时,此时栈顶元素必然是它的爷爷节点
// 取出并访问栈顶元素,赋值为right
else {
p = stack.pop();
System.out.print(p.data);
p = p.right;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值