您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法-第12章二叉树和其他树-002克隆二叉树

2016-03-19 16:36 387 查看
例子中二叉树用链表示

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
h
is the height of the binary tree being cloned
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: