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; } };
算法分析
解法一是自己写的,并不是十分简洁。但还可以了。解法二比较简洁,可以多学习学习。二叉树的翻转,一定要多多注意。程序分析
略。相关文章推荐
- Leetcode 226 Invert Binary Tree 反转二叉树
- Leetcode:226. Invert Binary Tree
- leetcode 226. Invert Binary Tree
- 【LEETCODE】226-Invert Binary Tree
- [leetcode] 226. Invert Binary Tree 解题报告
- LeetCode 226. Invert Binary Tree
- [LeetCode]226. Invert Binary Tree
- [leetcode] 226.Invert Binary Tree
- Leetcode 226: Invert Binary Tree(二叉树反转 递归、非递归实现)
- LeetCode-226. Invert Binary Tree
- Leetcode-226. Invert Binary Tree
- leetcode 226: Invert Binary Tree
- LeetCode 226. Invert Binary Tree(反转二叉树)
- leetcode 226. Invert Binary Tree
- Leetcode 226 Invert Binary Tree 二叉树
- leetcode 226--Invert Binary Tree
- leetcode(226)—— Invert Binary Tree(Python/C++)
- leetcode(62).226. Invert Binary Tree
- LeetCode226——Invert Binary Tree
- LeetCode 226. Invert Binary Tree