[LeetCode]Invert Binary Tree
来源:互联网 发布:网络用语so是什么意思 编辑:程序博客网 时间:2024/04/30 13:15
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.
思路:交换左右子节点,递归解决。 非递归用栈解决。
小伙伴快来试试看下谷歌是否有戏~~_(:зゝ∠)__(:зゝ∠)__(:зゝ∠)__(:зゝ∠)_
递归
/** * 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) { TreeNode *res = root; recursion(root); return res; } void recursion(TreeNode *root){ if(root==NULL) return; TreeNode *temp = root->left; root->left = root->right; root->right = temp; invertTree(root->left); invertTree(root->right); }};
非递归
/** * 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) { if(root==nullptr) return nullptr; stack<TreeNode*> stk; TreeNode *res = root; stk.push(root); while(!stk.empty()){ TreeNode* node = stk.top(); stk.pop(); if(node->left||node->right){ //非叶节点 TreeNode* temp = node->left; node->left = node->right; node->right = temp; } if(node->left)//注意空指针 stk.push(node->left); if(node->right) stk.push(node->right); } return res; }};
0 0
- [leetcode] Invert Binary Tree
- [LeetCode]Invert Binary Tree
- leetcode:Invert Binary Tree
- LeetCode Invert Binary Tree
- LeetCode | Invert Binary Tree
- leetcode--Invert Binary Tree
- [leetcode] Invert Binary Tree
- [LeetCode] Invert Binary Tree
- LeetCode Invert Binary Tree
- leetcode : Invert Binary Tree
- [LeetCode] Invert Binary Tree
- [Leetcode]Invert Binary Tree
- LeetCode: Invert Binary Tree
- LeetCode Invert Binary Tree
- leetcode: Invert Binary Tree
- LeetCode Invert Binary Tree
- LeetCode || Invert Binary Tree
- LeetCode:Invert Binary Tree
- 使用JMeter测试Web应用
- 如何使用Android MediaStore裁剪大图片
- tar文件的安装 基础
- 英语单词学习笔记
- wordpress文本编辑器百度UEditor中无法正常显示换行
- [LeetCode]Invert Binary Tree
- codeforces #549G Happy Line
- Doubles
- quick-cocos2dx的windows版如何显示标题栏下方的菜单栏
- CocoaPods 执行pod install很慢 没反应
- spring中集成TimerTask执行定时任务 中配置文件的配置
- quick-cocos2dx在xcode下如何添加额外的文件夹
- FaceBook/infer-bin目录下的文件说明
- 删除grub引导的linux双系统