数据结构与算法-第12章二叉树和其他树-002克隆二叉树
2016-03-19 16:36
387 查看
例子中二叉树用链表示
1.后序遍历克隆和前序遍历克隆
The recursion stack space needed by both the preorder and postorder copy methods is
1.后序遍历克隆和前序遍历克隆
package chapter12Tree; //In writing the cloning codes, we assume that we are not to //make clones of the elements in the nodes. Only the tree structure is to be cloned. //In case the elements are also to be cloned, then we must replace all occurrences //of element by code to first cast element into a CloneableObject, //and then invoke the method clone on the reulting object. public class BinaryTreeCloning { /** preorder cloning * @return root of clone */ public static BinaryTreeNode preOrderClone(BinaryTreeNode t) { if (t != null) {// nonempty tree // make a clone of the root BinaryTreeNode ct = new BinaryTreeNode(t.element); // now do the subtrees ct.leftChild = preOrderClone(t.leftChild); // clone left subtree ct.rightChild = preOrderClone(t.rightChild); // clone right subtree return ct; } else return null; } /** postorder cloning * @return root of clone */ public static BinaryTreeNode postOrderClone(BinaryTreeNode t) { if (t != null) {// nonempty tree // clone left subtree BinaryTreeNode cLeft = postOrderClone(t.leftChild); // clone right subtree BinaryTreeNode cRight = postOrderClone(t.rightChild); // clone root return new BinaryTreeNode(t.element, cLeft, cRight); } else return null; } } class BinaryTreeNode { int element; BinaryTreeNode leftChild, rightChild; // constructors BinaryTreeNode() {} BinaryTreeNode(int element) { this.element = element; this.rightChild = null; this.leftChild = null; } BinaryTreeNode(int element, BinaryTreeNode rc, BinaryTreeNode lc) { this.element = element; this.rightChild = rc; this.leftChild = lc; } }
The recursion stack space needed by both the preorder and postorder copy methods is
O(h), where
his the height of the binary tree being cloned
相关文章推荐
- 数据结构与算法-第12章二叉树和其他树-001遍历
- 【数据结构与算法】(七) c 语言实现一种快速排序算法
- [数据结构]散列表初识
- java数据结构排序之冒泡实现
- 链队列的模板类实现
- 重学数据结构系列之——队列
- java数据结构排序之归并排序实现
- java数据结构排序之希尔排序实现
- 经典算法与数据结构的c++实现——直接选择排序
- 数据结构与算法学习(四)
- 数据结构与算法JavaScript描述
- 和为S的连续正数序列
- 堆这种数据结构 Java实现
- 数据结构、算法与应用-第12章-001二叉树
- 和为S的两个数字
- 构建乘积数组
- 链表中环的入口结点
- 删除链表中重复的结点
- 对称的二叉树
- 二叉树的下一个结点