题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述
image.png分析
1.递归
//1.递归
public void Mirror(TreeNode root) {
if (root == null) return;
if (root.left == null && root.right == null) return;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
2.非递归
//2.非递归
public void Mirror(TreeNode root) {
if (root == null) return;
if (root.left == null && root.right == null) return;
Stack<TreeNode> stack = new Stack();
while (true) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
if (root.right != null) {
stack.push(root.right);
}
if (root.left != null) {
root = root.left;
} else {
if (stack.empty()) break;
root = stack.pop();
}
}
}
网友评论