Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
题意:翻转二叉树
分类:二叉树
解法1:递归。交换左右子节点,然后递归交换左右子树。
/**
* 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 null;
TreeNode t = root.left;
root.left = root.right;
root.right = t;
invertTree(root.left);
invertTree(root.right);
return root;
}
}