leetcode226

Invert a binary tree.
Example:
Input:
     4
   /   
  2     7
/    /
1   3 6   9
Output:
     4
   /   
  7     2
/    /
9   6 3   1
 
 
分治法
1.解决自己小三角,交换左右直接孩子。
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 invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        invertTree(root.left);
        invertTree(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/9741476.html