题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
核心
本题的核心点就是想办法遍历所有的节点,同时反转各个节点的左右子节点。
递归解法
基本思路
通过递归到达叶节点,然后从下往上将每个节点的左右子节点互换。
递归解法代码简洁,是通常给出的解法。但递归解法会消耗更多的堆栈,因此在此也给出了对应的循环解法。
以下为解答:
public void Mirror(TreeNode root) {
if (root == null) {
return;
}
Mirror(root.left);
Mirror(root.right);
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
循环解法
基本思路
该解法的核心是通过栈缓存节点。每次循环判断栈中是否有节点,若有则将栈中节点弹出并反转左右子节点,然后再将不为空的左右子节点压入栈,直到栈为空结束循环。
其处理方向正好和递归解法相反,是从上到下交换节点的左右子节点。
以下为解答:
public void Mirror(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
TreeNode tmp = cur.right;
cur.right = cur.left;
cur.left = tmp;
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
}