描述
翻转一棵二叉树。
示例
分析
反转二叉树,可以先交换根节点的两个子节点,然后通过同样的方式在交换根节点的子节点的两个子节点。
1.从root开始遍历二叉树;
2.只要当前节不为空,交换两个子节点;
3.对子节点重复上述步骤
实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
if(root.left!=null||root.right!=null){
TreeNode t = root.left;
root.left = root.right;
root.right = t ;
}
invertTree(root.left);
invertTree(root.right);
return root;
}
}