Friday, October 30, 2015

[leetcode] Binary Tree Upside Down

做这题的一个提升就是 先把recursive call当作能work的api.. 解决小问题先,再看小节 然后大问题其实就解决了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * 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 upsideDownBinaryTree(TreeNode root) {
     if (root == null || root.left == null){
      return root;
     }
        TreeNode one = upsideDownBinaryTree(root.right);
        TreeNode two = upsideDownBinaryTree(root.left);
        root.left.left = one;
        root.left.right = root;
        root.left = null;
        root.right = null;
        return two;
    }
}

No comments:

Post a Comment