剑指offer之二叉树镜像(Java实现)
题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
###解题思路:
解法一:
利用递归。先前序遍历这棵树的每个结点,如果遍历到的结点有子结点,就交换它的两个子节点,当交换完所有的非叶子结点的左右子结点之后,就得到了树的镜像。
public class Solution{
public void Mirror(TreeNode pRootOfTree){
if (pRootOfTree == null)
return;
if (pRootOfTree.left == null && pRootOfTree.right == null)
return;
TreeNode pTemp = pRootOfTree.left;
pRootOfTree.left = pRootOfTree.right;
pRootOfTree.right = pTemp;
if (pRootOfTree.left != null)
Mirror(pRootOfTree.left);
if (pRootOfTree.right != null)
Mirror(pRootOfTree.right);
}
}
解法二:
利用栈的非递归
import java.util.Stack;
public class Solution{
public void Mirror(TreeNode pRootOfTree){
if (pRootOfTree == null)
return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(pRootOfTree);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
if (node.left != null || node.right != null){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
if (node.left != null)
stack.push(node.left);
if (node.right != null)
stack.push(node.right);
}
}
}