Code & Func
2017-11-05

第41天。

今天的题目是Invert Binary Tree:

Invert a binary tree.

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

to

1
4
2
/ \
3
7 2
4
/ \ / \
5
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
TreeNode* invertTre1e(TreeNode* root) {
2
if (root == nullptr) return root;
3
TreeNode *left = invertTree(root->right);
4
TreeNode *right = invertTree(root->left);
5
root->left = left;
6
root->right = right;
7
return root;
8
}

然后是迭代的方法:

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