数据结构 (2) ——树 <IT小鸟每日一遍>
来源:互联网 发布:应聘软件测试工程师 编辑:程序博客网 时间:2024/05/09 20:55
树是一种一对多的结构,由结点与父节点到子结点的连线组成。
先看看普通的树怎样实现:
package com.wanq.datastructure.tree;import java.util.ArrayList;import java.util.List;/** * @author-WanQ * @创建时间:2013-3-21 下午03:53:40 * @类说明: * 普通的树 */public class CommonTree {protected TreeNode root;// 根节点public CommonTree() {root = new TreeNode();}public CommonTree(Object data) {root = new TreeNode(data);}/** * 遍历树头结点 * @return */public String traverseTree() {StringBuilder sb = new StringBuilder();if (root != null) {sb.append(root.toDataString() + "\n");for (TreeNode index : root.childList) {sb.append("\t"+index.toDataString() + "\n");if (index.childList != null && index.childList.size() > 0) {sb.append(traverseTree(index));}}}return sb.toString();}/** * 嵌套遍历树结点 * @param node * @return */public String traverseTree(TreeNode node) {StringBuilder sb = new StringBuilder();for (TreeNode index : node.childList) {sb.append("\t\t"+index.toDataString() + "\n");if (index.childList != null && index.childList.size() > 0) {sb.append(traverseTree(index));}}return sb.toString();}public TreeNode getRoot() {return root;}/** * 构建树 * @return */public CommonTree createTree() {CommonTree tree = new CommonTree("root");TreeNode node1 = new TreeNode("node1");TreeNode node2 = new TreeNode("node2");TreeNode node3 = new TreeNode("node3");TreeNode node4 = new TreeNode("node4");TreeNode node1_1 = new TreeNode("node1_1");TreeNode node1_2 = new TreeNode("node1_2");TreeNode node1_3 = new TreeNode("node1_3");TreeNode node2_1 = new TreeNode("node2_1");node1.getChildList().add(0, node1_1);node1.getChildList().add(1, node1_2);node1.getChildList().add(0, node1_3);node2.getChildList().add(0, node2_1);tree.getRoot().getChildList().add(0, node1);tree.getRoot().getChildList().add(1, node2);tree.getRoot().getChildList().add(2, node3);tree.getRoot().getChildList().add(3, node4);return tree;}public static void main(String[] args) {CommonTree tree = new CommonTree().createTree();System.out.println(tree.traverseTree());}/** * 树结点类 * @author WanQ * */public class TreeNode {Object data;List<TreeNode> childList;public TreeNode() {this.data = new Object();this.childList = new ArrayList<TreeNode>();}public TreeNode(Object data) {this.data = data;this.childList = new ArrayList<TreeNode>();}public Object getData() {return this.data;}public String getDataString() {return ((NodeBean) this.data).getBeanString();}public String toDataString() {return this.data.toString();}public List<TreeNode> getChildList() {return this.childList;}}public class NodeBean {String name;public void setName(String str) {this.name = str;}public String getName() {return this.name;}public String getBeanString() {return "NodeBean [name=" + name + "]\n";}@Overridepublic String toString() {return "NodeBean [name=" + name + "]\n";}}}
package com.wanq.datastructure.tree;import java.util.Stack;/** * @author-WanQ * @创建时间:2013-3-21 下午10:00:15 * @类说明: 二叉树 * */public class BinaryTree {protected BinaryTreeNode root;// 根节点public BinaryTree(BinaryTreeNode root) {this.root = root;}public BinaryTreeNode getRoot() {return root;}/** * 初始化 二叉树 * @return */public static BinaryTreeNode init() {BinaryTreeNode a = new BinaryTreeNode('A');BinaryTreeNode b = new BinaryTreeNode('B', null, a);BinaryTreeNode c = new BinaryTreeNode('C');BinaryTreeNode d = new BinaryTreeNode('D', b, c);BinaryTreeNode e = new BinaryTreeNode('E');BinaryTreeNode f = new BinaryTreeNode('F', e, null);BinaryTreeNode g = new BinaryTreeNode('G', null, f);BinaryTreeNode h = new BinaryTreeNode('H', d, g);return h;}/** 访问节点 */public static void visit(BinaryTreeNode p) {System.out.print(p.getKey() + " ");}/** 递归实现前序遍历 */protected static void preorder(BinaryTreeNode p) {if (p != null) {visit(p);preorder(p.getLeft());preorder(p.getRight());}}/** 递归实现中序遍历 */protected static void inorder(BinaryTreeNode p) {if (p != null) {inorder(p.getLeft());visit(p);inorder(p.getRight());}}/** 递归实现后序遍历 */protected static void postorder(BinaryTreeNode p) {if (p != null) {postorder(p.getLeft());postorder(p.getRight());visit(p);}}/** 非递归实现前序遍历 */protected static void iterativePreorder(BinaryTreeNode p) {Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();if (p != null) {stack.push(p);while (!stack.empty()) {p = stack.pop();visit(p);if (p.getRight() != null)stack.push(p.getRight());if (p.getLeft() != null)stack.push(p.getLeft());}}}/** 非递归实现后序遍历 */protected static void iterativePostorder(BinaryTreeNode p) {BinaryTreeNode q = p;Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();while (p != null) {// 左子树入栈for (; p.getLeft() != null; p = p.getLeft())stack.push(p);// 当前节点无右子或右子已经输出while (p != null && (p.getRight() == null || p.getRight() == q)) {visit(p);q = p;// 记录上一个已输出节点if (stack.empty())return;p = stack.pop();}// 处理右子stack.push(p);p = p.getRight();}}/** 非递归实现中序遍历 */protected static void iterativeInorder(BinaryTreeNode p) {Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();while (p != null) {while (p != null) {if (p.getRight() != null)stack.push(p.getRight());// 当前节点右子入栈stack.push(p);// 当前节点入栈p = p.getLeft();}p = stack.pop();while (!stack.empty() && p.getRight() == null) {visit(p);p = stack.pop();}visit(p);if (!stack.empty())p = stack.pop();elsep = null;}}public static void main(String[] args) {BinaryTree tree = new BinaryTree(init());System.out.print(" Pre-Order:");preorder(tree.getRoot());System.out.println();System.out.print(" In-Order:");inorder(tree.getRoot());System.out.println();System.out.print("Post-Order:");postorder(tree.getRoot());System.out.println();System.out.print(" Pre-Order:");iterativePreorder(tree.getRoot());System.out.println();System.out.print(" In-Order:");iterativeInorder(tree.getRoot());System.out.println();System.out.print("Post-Order:");iterativePostorder(tree.getRoot());System.out.println();}/** * 二叉树结点-内部类 * @author WanQ * */public static class BinaryTreeNode{private char key;private BinaryTreeNode left, right;public BinaryTreeNode(char key) {this(key, null, null);}public BinaryTreeNode(char key, BinaryTreeNode left, BinaryTreeNode right) {this.key = key;this.left = left;this.right = right;}public char getKey() {return key;}public void setKey(char key) {this.key = key;}public BinaryTreeNode getLeft() {return left;}public void setLeft(BinaryTreeNode left) {this.left = left;}public BinaryTreeNode getRight() {return right;}public void setRight(BinaryTreeNode right) {this.right = right;}}}
二叉查找树
package com.wanq.datastructure.tree.temp;import java.util.ArrayList;import java.util.List;/** * @author-WanQ * @创建时间:2013-3-21 下午10:13:57 * @类说明: * */public class BinarySearchTree { // 树的根结点 private TreeNode root = null; // 遍历结点列表 private List<TreeNode> nodelist = new ArrayList<TreeNode>(); private class TreeNode { private int key; private TreeNode leftChild; private TreeNode rightChild; private TreeNode parent; public TreeNode(int key, TreeNode leftChild, TreeNode rightChild, TreeNode parent) { this.key = key; this.leftChild = leftChild; this.rightChild = rightChild; this.parent = parent; } public int getKey() { return key; } public String toString() { String leftkey = (leftChild == null ? "" : String .valueOf(leftChild.key)); String rightkey = (rightChild == null ? "" : String .valueOf(rightChild.key)); return "(" + leftkey + " , " + key + " , " + rightkey + ")"; } } /** * isEmpty: 判断二叉查找树是否为空;若为空,返回 true ,否则返回 false . * */ public boolean isEmpty() { if (root == null) { return true; } else { return false; } } /** * TreeEmpty: 对于某些二叉查找树操作(比如删除关键字)来说,若树为空,则抛出异常。 */ public void TreeEmpty() throws Exception { if (isEmpty()) { throw new Exception("树为空!"); } } /** * search: 在二叉查找树中查询给定关键字 * * @param key * 给定关键字 * @return 匹配给定关键字的树结点 */ public TreeNode search(int key) { TreeNode pNode = root; while (pNode != null && pNode.key != key) { if (key < pNode.key) { pNode = pNode.leftChild; } else { pNode = pNode.rightChild; } } return pNode; } /** * minElemNode: 获取二叉查找树中的最小关键字结点 * * @return 二叉查找树的最小关键字结点 * @throws Exception * 若树为空,则抛出异常 */ public TreeNode minElemNode(TreeNode node) throws Exception { if (node == null) { throw new Exception("树为空!"); } TreeNode pNode = node; while (pNode.leftChild != null) { pNode = pNode.leftChild; } return pNode; } /** * maxElemNode: 获取二叉查找树中的最大关键字结点 * * @return 二叉查找树的最大关键字结点 * @throws Exception * 若树为空,则抛出异常 */ public TreeNode maxElemNode(TreeNode node) throws Exception { if (node == null) { throw new Exception("树为空!"); } TreeNode pNode = node; while (pNode.rightChild != null) { pNode = pNode.rightChild; } return pNode; } /** * successor: 获取给定结点在中序遍历顺序下的后继结点 * * @param node * 给定树中的结点 * @return 若该结点存在中序遍历顺序下的后继结点,则返回其后继结点;否则返回 null * @throws Exception */ public TreeNode successor(TreeNode node) throws Exception { if (node == null) { return null; } // 若该结点的右子树不为空,则其后继结点就是右子树中的最小关键字结点 if (node.rightChild != null) { return minElemNode(node.rightChild); } // 若该结点右子树为空 TreeNode parentNode = node.parent; while (parentNode != null && node == parentNode.rightChild) { node = parentNode; parentNode = parentNode.parent; } return parentNode; } /** * precessor: 获取给定结点在中序遍历顺序下的前趋结点 * * @param node * 给定树中的结点 * @return 若该结点存在中序遍历顺序下的前趋结点,则返回其前趋结点;否则返回 null * @throws Exception */ public TreeNode precessor(TreeNode node) throws Exception { if (node == null) { return null; } // 若该结点的左子树不为空,则其前趋结点就是左子树中的最大关键字结点 if (node.leftChild != null) { return maxElemNode(node.leftChild); } // 若该结点左子树为空 TreeNode parentNode = node.parent; while (parentNode != null && node == parentNode.leftChild) { node = parentNode; parentNode = parentNode.parent; } return parentNode; } /** * insert: 将给定关键字插入到二叉查找树中 * * @param key * 给定关键字 */ public void insert(int key) { TreeNode parentNode = null; TreeNode newNode = new TreeNode(key, null, null, null); TreeNode pNode = root; if (root == null) { root = newNode; return; } while (pNode != null) { parentNode = pNode; if (key < pNode.key) { pNode = pNode.leftChild; } else if (key > pNode.key) { pNode = pNode.rightChild; } else { // 树中已存在匹配给定关键字的结点,则什么都不做直接返回 return; } } if (key < parentNode.key) { parentNode.leftChild = newNode; newNode.parent = parentNode; } else { parentNode.rightChild = newNode; newNode.parent = parentNode; } } /** * insert: 从二叉查找树中删除匹配给定关键字相应的树结点 * * @param key * 给定关键字 */ public void delete(int key) throws Exception { TreeNode pNode = search(key); if (pNode == null) { throw new Exception("树中不存在要删除的关键字!"); } delete(pNode); } /** * delete: 从二叉查找树中删除给定的结点. * * @param pNode * 要删除的结点 * * 前置条件: 给定结点在二叉查找树中已经存在 * @throws Exception */ private void delete(TreeNode pNode) throws Exception { if (pNode == null) { return; } if (pNode.leftChild == null && pNode.rightChild == null) { // 该结点既无左孩子结点,也无右孩子结点 TreeNode parentNode = pNode.parent; if (pNode == parentNode.leftChild) { parentNode.leftChild = null; } else { parentNode.rightChild = null; } return; } if (pNode.leftChild == null && pNode.rightChild != null) { // 该结点左孩子结点为空,右孩子结点非空 TreeNode parentNode = pNode.parent; if (pNode == parentNode.leftChild) { parentNode.leftChild = pNode.rightChild; pNode.rightChild.parent = parentNode; } else { parentNode.rightChild = pNode.rightChild; pNode.rightChild.parent = parentNode; } return; } if (pNode.leftChild != null && pNode.rightChild == null) { // 该结点左孩子结点非空,右孩子结点为空 TreeNode parentNode = pNode.parent; if (pNode == parentNode.leftChild) { parentNode.leftChild = pNode.leftChild; pNode.rightChild.parent = parentNode; } else { parentNode.rightChild = pNode.leftChild; pNode.rightChild.parent = parentNode; } return; } // 该结点左右孩子结点均非空,则删除该结点的后继结点,并用该后继结点取代该结点 TreeNode successorNode = successor(pNode); delete(successorNode); pNode.key = successorNode.key; } /** * inOrderTraverseList: 获得二叉查找树的中序遍历结点列表 * * @return 二叉查找树的中序遍历结点列表 */ public List<TreeNode> inOrderTraverseList() { if (nodelist != null) { nodelist.clear(); } inOrderTraverse(root); return nodelist; } /** * inOrderTraverse: 对给定二叉查找树进行中序遍历 * * @param root * 给定二叉查找树的根结点 */ private void inOrderTraverse(TreeNode root) { if (root != null) { inOrderTraverse(root.leftChild); nodelist.add(root); inOrderTraverse(root.rightChild); } } /** * toStringOfOrderList: 获取二叉查找树中关键字的有序列表 * * @return 二叉查找树中关键字的有序列表 */ public String toStringOfOrderList() { StringBuilder sbBuilder = new StringBuilder(" [ "); for (TreeNode p : inOrderTraverseList()) { sbBuilder.append(p.key); sbBuilder.append(" "); } sbBuilder.append("]"); return sbBuilder.toString(); } /** * 获取该二叉查找树的字符串表示 */ public String toString() { StringBuilder sbBuilder = new StringBuilder(" [ "); for (TreeNode p : inOrderTraverseList()) { sbBuilder.append(p); sbBuilder.append(" "); } sbBuilder.append("]"); return sbBuilder.toString(); } public TreeNode getRoot() { return root; } public static void testNode(BinarySearchTree bst, TreeNode pNode) throws Exception { System.out.println("本结点: " + pNode); System.out.println("前趋结点: " + bst.precessor(pNode)); System.out.println("后继结点: " + bst.successor(pNode)); } public static void testTraverse(BinarySearchTree bst) { System.out.println("二叉树遍历:" + bst); System.out.println("二叉查找树转换为有序列表: " + bst.toStringOfOrderList()); } public static void main(String[] args) { try { BinarySearchTree bst = new BinarySearchTree(); System.out.println("查找树是否为空? " + (bst.isEmpty() ? "是" : "否")); int[] keys = new int[] { 15, 6, 18, 3, 7, 13, 20, 2, 9, 4 }; for (int key : keys) { bst.insert(key); } System.out.println("查找树是否为空? " + (bst.isEmpty() ? "是" : "否")); TreeNode minkeyNode = bst.minElemNode(bst.getRoot()); System.out.println("最小关键字: " + minkeyNode.getKey()); testNode(bst, minkeyNode); TreeNode maxKeyNode = bst.maxElemNode(bst.getRoot()); System.out.println("最大关键字: " + maxKeyNode.getKey()); testNode(bst, maxKeyNode); System.out.println("根结点关键字: " + bst.getRoot().getKey()); testNode(bst, bst.getRoot()); testTraverse(bst); System.out.println("****************************** "); testTraverse(bst); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
- 数据结构 (2) ——树 <IT小鸟每日一遍>
- 数据结构 (3) ——排序 <IT小鸟每日一遍>
- 数据结构 (1) ——线性表 <IT小鸟每日一遍>
- 设计模式 (2) ——工厂方法模式 <IT小鸟每日一遍>
- 设计模式 (1) ——单例模式 <IT小鸟每日一遍>
- 设计模式 (3) ——抽象工厂模式 <IT小鸟每日一遍>
- 设计模式 (4) ——模板模式 <IT小鸟每日一遍>
- 设计模式 (5) ——建造者模式 <IT小鸟每日一遍>
- 设计模式 (6) ——代理模式 <IT小鸟每日一遍>
- 同是IT小小鸟——《我是一只IT小小鸟》读书笔记
- 《我是一只IT小小鸟》连载之二——梦断计院(2)
- 《我是一只IT小小鸟》连载之四——为梦前行(2)
- 《我是一只IT小小鸟》连载十一——再难也要向前爬(2)
- 兴趣·热情·团队——《我是一只IT小小鸟》读书笔记(2)
- 《我是一只IT小小鸟》连载六——掉进读书的兔子洞(2)
- 摘自【《我是一只IT小小鸟》连载之四——为梦前行(2)】
- 《我是一只IT小小鸟》连载六——掉进读书的兔子洞(2)
- 关于坚持关于喜欢然后想做——读《我是一只IT小小鸟》
- 串口实用的循环缓冲区
- zoj 3210 A Stack or A Queue?
- phpmyadmin密码问题
- 大整数相加
- 杭州蓝联
- 数据结构 (2) ——树 <IT小鸟每日一遍>
- NYIST546-Divideing Jewels
- 2013-03-08 00:27 TFT LCD控制器
- Hdu4502 吉哥系列故事——临时工计划 (dp)
- Prototyping Tools Comparison
- 卡特兰数
- Aache和tomcat区别
- framebuffer驱动
- Unity3D工程与MonoDevelop工具调试