Invert Binary Tree

第41天。

今天的题目是Invert Binary Tree:

Invert a binary tree.

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

to

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

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

emmmm,挺出名的一道题目。

其实挺简单:

1
2
3
4
5
6
7
8
TreeNode* invertTre1e(TreeNode* root) {
if (root == nullptr) return root;
TreeNode *left = invertTree(root->right);
TreeNode *right = invertTree(root->left);
root->left = left;
root->right = right;
return root;
}

然后是迭代的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
TreeNode* invertTree(TreeNode *root) {
stack<TreeNode *> st;
st.push(root);
TreeNode *ret =root;
while(!st.empty()) {
root = st.top();
st.pop();
if (root) {
st.push(root->left);
st.push(root->right);
TreeNode *t = root->left;
root->left = root->right;
root->right = t;
}
}
return ret;
}