226. Invert Binary Tree
来源:互联网 发布:c语言中stdlib 编辑:程序博客网 时间:2024/06/06 00:58
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9to
4 / \ 7 2 / \ / \9 6 3 1
我的解法:
/** * 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: void Invert(TreeNode* root){ if(root){ TreeNode* temp = root->left; root->left = root->right; root->right = temp; if(root->left)invertTree(root->left); if(root->right)invertTree(root->right); }else{ return; } } TreeNode* invertTree(TreeNode* root) { Invert(root); return root; }};写的很臃肿,下面式别人的简洁的
Recursive
TreeNode* invertTree(TreeNode* root) { if (root) { invertTree(root->left); invertTree(root->right); std::swap(root->left, root->right); } return root;}下面这个是用栈实现的非迭代的。
TreeNode* invertTree(TreeNode* root) { std::stack<TreeNode*> stk; stk.push(root); while (!stk.empty()) { TreeNode* p = stk.top(); stk.pop(); if (p) { stk.push(p->left); stk.push(p->right); std::swap(p->left, p->right); } } return root;}
阅读全文
0 0
- 226.Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 红黑树的基本操作
- MyBatis 02
- List,Set,Map是否继承自Collection接口?
- csuoj1640机智的刷题方式(背包)
- java原生实现webservice
- 226. Invert Binary Tree
- 关于 IE8 console不未定义的问题
- jQuery插件--Validation
- jquery实现选项卡切换
- 数据库设计
- [JS] SpringMVC环境下配置ArcGIS JS跨域访问(代理服务)
- 一、python的下载与安装
- Django
- Linux窗口下命令