2、题目:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell :
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.2、思路:
1)采用深度遍历每一层,每处理一层时,将该层的值放入stack数组中;
2)每遍历一层后,再重复遍历该层,此时将stack中的值取出,放入到树中。
3、自己的代码(未通过):
/**
* 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) {
queue<TreeNode*> que1;
queue<TreeNode*> que2;
stack<int> s;
int i,j,n;
que1.push(root);
que2.push(root);
if(root==NULL)
return NULL;
while(!que1.empty()){
n=que1.size();
TreeNode*q=que1.front();
for(i=0;i<n;i++){
TreeNode*q1=que1.front();
que1.pop();
if(q1->left!=NULL){
que1.push(q1->left);
s.push(q1->left->val);
}
if(q1->right!=NULL){
que1.push(q1->right);
s.push(q1->right->val);
}
}
for(i=0;i<n;i++){
TreeNode*q2=que2.front();
que2.pop();
if(q2->left!=NULL){
cout<<s.top()<<endl;
que2.push(q2->left);
q2->left->val=s.top();
s.pop();
}
if(q2->right!=NULL){
cout<<s.top()<<endl;
que2.push(q2->right);
q2->right->val=s.top();
s.pop();
}
}
}
return root;
}
};
4、自己的代码没通过。原因:null值不值得怎么处理:
例如[1,2],我的代码是转为[1,2],答案是[1,null,2],
又如[1,null,3],我的代码转换为[1,null,3],答案是[1,3]
5、在讨论区中答案:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return NULL;
// swap left and right child
TreeNode *temp = invertTree(root->left);
root->left = invertTree(root->right);
root->right = temp;
return root;
}
};
6、java实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null)
return null;
TreeNode temp=invertTree(root.left);
root.left=invertTree(root.right);
root.right=temp;
return root;
}
}
7、自己好弱啊,加油吧!