-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path226_Invert_Binary_Tree.cpp
54 lines (47 loc) · 1011 Bytes
/
226_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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
// 1. 递归(推荐)
if (!root) return root;
TreeNode* tmp;
tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
// 2. 循环,亦可
//if (!root) return root;
//queue<TreeNode*> q;
//q.push(root);
//while (!q.empty()) {
// TreeNode* r = q.front();
// q.pop();
// TreeNode* tmp = r->left;
// r->left = r->right;
// r->right = tmp;
// if (r->left) q.push(r->left);
// if (r->right) q.push(r->right);
//}
//return root;
}
};