LeetCode 226. Invert Binary Tree

原题链接在这里:https://leetcode.com/problems/invert-binary-tree/

题目:

Invert a binary tree.

     4
   /   
  2     7
 /    / 
1   3 6   9

to

     4
   /   
  7     2
 /    / 
9   6 3   1

题解:

既可以自顶向下,也可以自底向上.

Time Complexity: O(n). Space: O(logn).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode invertTree(TreeNode root) {
12         /*
13         //Method 1 自顶向下
14         if(root == null){
15             return root;
16         }
17         TreeNode temp = root.left;
18         root.left = root.right;
19         root.right = temp;
20         invertTree(root.left);
21         invertTree(root.right);
22         return root;
23         */
24         
25         //Method 2 自底向上
26         if(root == null){
27             return root;
28         }
29         TreeNode tempLeft = root.left;
30         root.left = invertTree(root.right);
31         root.right = invertTree(tempLeft);
32         return root;
33     }
34 }

AC JavaScript:

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {TreeNode}
11  */
12 var invertTree = function(root) {
13     if(!root){
14         return root;
15     }
16     
17     var l = invertTree(root.left);
18     var r = invertTree(root.right);
19     root.left = r;
20     root.right = l;
21     return root;
22 };
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824988.html