[LeetCode] 226. Invert Binary Tree

翻转二叉树。也是一道不会做,会写homebrew也枉然的题。题干即是题意。例子如下,即层层遍历,把左右子树交换。

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

两种思路,分别是层序遍历(BFS)和深度遍历(DFS)。

DFS

时间O(n)

空间O(n)

 1 /**
 2  * @param {TreeNode} root
 3  * @return {TreeNode}
 4  */
 5 var invertTree = function(root) {
 6     if (root === null) return root;
 7     let left = invertTree(root.left);
 8     let right = invertTree(root.right);
 9     root.left = right;
10     root.right = left;
11     return root;
12 };

 

BFS

时间O(n)

空间O(n)

 1 /**
 2  * @param {TreeNode} root
 3  * @return {TreeNode}
 4  */
 5 var invertTree = function(root) {
 6     if (!root) return root;
 7     let queue = [root];
 8     while (queue.length) {
 9         let current = queue.shift();
10         if (current === null) continue;
11         swap(current);
12         queue.push(current.left);
13         queue.push(current.right);
14     }
15     return root;
16 };
17 
18 var swap = tree => {
19     let temp = tree.left;
20     tree.left = tree.right;
21     tree.right = temp;
22     return tree;
23 };

你可能感兴趣的:([LeetCode] 226. Invert Binary Tree)