您的位置:首页 > 其它

输入一颗二元查找树,将该树转换为它的镜像

2012-05-14 23:10 417 查看
题目:输入一颗二元查找树,将该树转换为它的镜像,

即在转换后的二元查找树中,左子树的结点都大于右子树的结点。

用递归和循环两种方法完成树的镜像转换。

例如输入:

8

/ /

6 10

// //

5 7 9 11

输出:

8

/ /

10 6

// //

11 9 7 5

定义二元查找树的结点为:

struct BSTreeNode // a node in the binary search tree (BST)

{

int m_nValue; // value of node

BSTreeNode *m_pLeft; // left child of node

BSTreeNode *m_pRight; // right child of node

};

public static void mirrorHelp1(Node node){
if(node==null)return;
swapChild(node);
mirrorHelp1(node.getLeft());
mirrorHelp1(node.getRight());
}
//use no recursion but stack
public static void mirrorHelp2(Node node){
if(node==null)return;
Stack<Node> stack=new Stack<Node>();
stack.add(node);
while(!stack.isEmpty()){
node=stack.pop();
swapChild(node);
if(node.getLeft()!=null){
stack.push(node.getLeft());
}
if(node.getRight()!=null){
stack.push(node.getRight());
}

}
}

public static void swapChild(Node node){
/*not like c/c++,you cannot do this:
Node temp=left;
left=right;
right=temp;
*/
Node left=node.getLeft();
node.setLeft(node.getRight());
node.setRight(left);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐