操作给定的二叉树,将其变换为源二叉树的镜像。
其他方法
方法1:递归代码
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeNode Mirror(TreeNode root) {
//1 先判断传入的这个树是否为空
if(root == null) return null;
//2 树不为空,我们就递归处理子树,先把左子树暂存起来
TreeNode tempNode;
tempNode = root.left;//暂存root的左子节点
//2.1 先把root的右子节点递归反转,返回值赋值给root左子节点
root.left = Mirror(root.right);
//处理一开始暂存的root的左子树,赋值给该节点的右子树
root.right = Mirror(tempNode);
//返回root树
return root;
}
}
方法2:前序遍历代码(递归)
//方法2:前序遍历
public TreeNode Mirror(TreeNode root) {
if(root==null) return root;
//根
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//左递归
Mirror(root.left);
//右递归
Mirror(root.right);
//返回结果
return root;
}
方法3:借用栈
方法4:借用队列
原文:https://www.cnblogs.com/jiyongjia/p/13191831.html