题目描述
Invert a binary tree.
题目分析
将二叉树翻转,通过不断递归实现二叉树的翻转。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null)
return root;
TreeNode temp=root.left;//临时变量,实现交换
root.left=root.right;
root.right=temp;
invertTree(root.left);//不断递归
invertTree(root.right);
return root;
}
}