forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0226-invert-binary-tree.cpp
33 lines (30 loc) · 878 Bytes
/
0226-invert-binary-tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
Given the root of a binary tree, invert the tree, and return its root
Ex. root = [4,2,7,1,3,6,9] -> [4,7,2,9,6,3,1], [2,1,3] -> [2,3,1]
Preorder traversal, at each node, swap it's left and right children
Time: O(n)
Space: O(n)
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
classSolution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) {
returnNULL;
}
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};