您的位置:首页 > 其它

LeetCode-226. Invert Binary Tree

2018-04-03 16:39 423 查看

Description

Invert a binary tree.

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

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


Tips

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


Solution 1(C++)

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0;}();
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return root;
TreeNode* temp = NULL;
if(root->left && root->right){
temp=root->left;
root->left=invertTree(root->right);
root->right=invertTree(temp);
}
else if(!root->left && !root->right){}
else{
if(root->left){root->right=invertTree(root->left); root->left=NULL;}
else{root->left=invertTree(root->right); root->right=NULL;}
}
return root;
}
};


Solution 2(C++)

class Solution {
public:
void invertTreeRecurs(TreeNode* node) {
if (node == NULL) return;

TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp;

invertTreeRecurs(node->left);
invertTreeRecurs(node->right);
}

TreeNode* invertTree(TreeNode* root) {
invertTreeRecurs(root);

return root;
}
};


算法分析

解法一是自己写的,并不是十分简洁。但还可以了。解法二比较简洁,可以多学习学习。二叉树的翻转,一定要多多注意。

程序分析

略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: