leetcode226 - Invert Binary Tree - easy

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;
    }
}

 

posted @ 2018-10-04 03:15  jasminemzy  阅读(250)  评论(0编辑  收藏  举报