题目:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
思路:
递归:递归结束条件(null时)+递归模块(左右子树节点交换,递归遍历左右子树)
程序:
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
TreeNode tree = root.right;
root.right = root.left;
root.left = tree;
invertTree(root.right);
invertTree(root.left);
return root;
}
}