二叉树的三种地柜方式

public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree(); // 输入ABDH##I##E##CF#J##G##(#用null代替) LinkedList tree = new LinkedList(); 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 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 treeData) { TreeNode root = null; T data = treeData.removeFirst(); if (data != null) { root = new TreeNode(data, null, null); root.left = creatBinaryPre(treeData); root.right = creatBinaryPre(treeData); } return root; } public void PrintBinaryTreePreRecur(TreeNode root) { if (root != null) { System.out.println(root.data); PrintBinaryTreePreRecur(root.left); PrintBinaryTreePreRecur(root.right); } } @SuppressWarnings(“unchecked”) public void PrintBinaryTreePreUnRecur(TreeNode root) { TreeNode p = root; LinkedList stack = new LinkedList(); while (p != null && !stack.isEmpty()) { if (p != null) { stack.push§; System.out.println(p.data); p = p.left; } else { p = stack.pop(); p = p.right; } } } public void PrintBinaryTreeMidRecur(TreeNode root) { if (root != null) { PrintBinaryTreeMidRecur(root.left); System.out.println(root.data); PrintBinaryTreeMidRecur(root.right); } } public void PrintBinaryTreeMidUnrecur(TreeNode root) { TreeNode p = root;// p为当前节点 LinkedList stack = new LinkedList(); // 栈不为空时,或者p不为空时循环 while (p != null || !stack.isEmpty()) { // 当前节点不为空。压入栈中。并将当前节点赋值为左儿子 if (p != null) { stack.push§; p = p.left; } // 当前节点为空: // 1、当p指向的左儿子时,此时栈顶元素必然是它的父节点 // 2、当p指向的右儿子时,此时栈顶元素必然是它的爷爷节点 // 取出并访问栈顶元素,赋值为right else { p = stack.pop(); System.out.print(p.data); p = p.right; } } }


本文来自 言寡 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/qq_21406125/article/details/79421279?utm_source=copy

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值