题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。
方法一:递归
思路:去掉空树、单节点的情况,将左子树临时保存,右子树赋值给左子树,递归进行交换。
public static void MirrorRecursively(TreeNode root) {
if (root == null)
return ;
if (root.left == null && root.right == null)
return ;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if (root.left != null)
MirrorRecursively(root.left);
if (root.right != null)
MirrorRecursively(root.right);
}
方法二:循环
思路:使用栈进行辅助。将树的右节点压入栈中,之后弹出进行交换左右子树。
public static void MirrorRecursively(TreeNode root) {
// 空树或者只有一个节点
if (root == null)
return ;
if (root.left == null && root.right == null)
return ;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
TreeNode nodep = null;
while (stack != null || nodep != null) {
// nodep还是上一点的left或者是stack里面的节点
if (nodep == null && !stack.isEmpty())
nodep = stack.pop();
if (nodep == null)
return ;
// 交换左右节点
if (nodep.left != null || nodep.right != null) {
TreeNode tmp = nodep.left;
nodep.left = nodep.right;
nodep.right = tmp;
}
// 右节点压栈
if (nodep.right != null)
stack.push(nodep.right);
nodep = nodep.left; // 直接赋值,while最开始会判断
}
}