您的位置:首页 > 职场人生

面试题19 二叉树的镜像

2016-06-14 00:49 316 查看

题目:

输入一个二叉树,输出该二叉树的镜像

输入:

二叉排序树的前序遍历:8 2 4 7 9 10

输出:

该二叉树的镜像的前序遍历:8 9 10 2 4 7

解题思路:

本质上就是不停的交换二叉树的左子树和右子树,直到树的叶节点或者节点为空。

Java代码实现:

public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode node=new TreeNode();
node.insert(8);
node.insert(9);
node.insert(2);
node.insert(4);
node.insert(7);
node.insert(10);
node.oneDisplay(node.root);
MirrorRecursively(node.root);
System.out.println();
node.oneDisplay(node.root);

}

//递归调用,递归结束的条件是到了叶节点或者该节点为空
public static Node MirrorRecursively(Node pNode){

if(pNode==null ||(pNode.leftChild==null && pNode.rightChild==null)){
return null;
}
Node temp=null;
temp=pNode.leftChild;
pNode.leftChild=pNode.rightChild;
pNode.rightChild=temp;

MirrorRecursively(pNode.leftChild);
MirrorRecursively(pNode.rightChild);

return pNode;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: