目录
题目描述:
递归代码1:
递归代码2:
非递归代码(层次遍历):
题目描述:
给定一棵二叉树的根节点 root,请左右翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [5,7,9,8,3,2,4]
输出:[5,9,7,4,2,3,8]
递归代码1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null){
return null;
}
TreeNode result=new TreeNode(root.val);
getResult(root,result);
return result;
}
public void getResult(TreeNode root,TreeNode copyRoot){
if(root.right!=null){
TreeNode node=new TreeNode(root.right.val);
copyRoot.left=node;
getResult(root.right,copyRoot.left);
}
if(root.left!=null){
TreeNode node=new TreeNode(root.left.val);
copyRoot.right=node;
getResult(root.left,copyRoot.right);
}
}
}
递归代码2:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
fn(root);
return root;
}
public void fn(TreeNode root){
if(root==null){
return ;
}
TreeNode t=root.left;
root.left=root.right;
root.right=t;
fn(root.left);
fn(root.right);
}
}
非递归代码(层次遍历):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null){
return null;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode node=queue.remove();
TreeNode t=node.right;
node.right=node.left;
node.left=t;
if(node.right!=null){
queue.add(node.right);
}
if(node.left!=null){
queue.add(node.left);
}
}
}
return root;
}
}