1 题目
2 源码
public static void SetMirrorRecursively(BinaryTreeNode root)
{
if (root == null || (root.leftChild == null && root.rightChild == null))
{
return;
}
// 交换
BinaryTreeNode tempNode = root.leftChild;
root.leftChild = root.rightChild;
root.rightChild = tempNode;
if (root.leftChild != null) {
// 递归调整左子树为镜像
SetMirrorRecursively(root.leftChild);
}
if (root.rightChild != null) {
// 递归调整右子树为镜像
SetMirrorRecursively(root.rightChild);
}
}
public static void SetMirrorIteratively(BinaryTreeNode root) {
if (root == null){
return;
}
// 压栈深度优先
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
stack.Push(root);
while (stack.count > 0)
{
BinaryTreeNode node = stack.Pop();
// 交换
BinaryTreeNode temp = node.leftChild;
node.leftChild = node.rightChild;
node.rightChild = temp;
// 先压右子树
if (node.rightChild != null){
stack.Push(node.rightChild);
}
// 再压左子树
if (node.leftChild != null){
stack.Push(node.leftChild);
}
}
}