algorithm notes: leetcode#226 invert binary tree

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class :
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root is None:
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class {
public TreeNode invertTree(TreeNode root) {
if(root != null){
TreeNode t = root.left;
root.left = root.right;
root.right = t;
invertTree(root.left);
invertTree(root.right);}
return root;
}
}

Time complexity

O(N).

Space complexity

O(L).


226. Invert Binary Tree
(中文版) 算法笔记: 力扣#226 翻转二叉树