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
3万+

被折叠的 条评论
为什么被折叠?



