题目:操作给定的二叉树,将其变换为源二叉树的镜像。
思路:画图分析可知,在遍历二叉树的过程中将节点的左右子树交换即可。
代码(递归实现,已在牛客网AC):
public void Mirror(TreeNode root) {
if(root == null)
return;
if(root.left == null && root.right == null)
return;
exch(root);
Mirror(root.left);
Mirror(root.right);
}
private void exch(TreeNode root){
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
非递归实现:
public void Mirror(TreeNode root) {
if(root == null)
return;
if(root.left == null && root.right == null)
return;
Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.empty())
{
while(root != null)
{
exch(root);
stack.push(root);
root = root.left;
}
if(!stack.empty())
{
TreeNode node = stack.pop();
root = node.right;
}
}
}
private void exch(TreeNode root){
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}