Lintcode 二叉树的中序遍历
来源:互联网 发布:ping远程ip的8080端口 编辑:程序博客网 时间:2024/05/21 10:44
给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
挑战
你能使用非递归算法来实现么?
标签
方法一 递归/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */public: void inorder(TreeNode *root,vector<int> &result) { if(root->left!=NULL) inorder(root->left,result); result.push_back(root->val); if(root->right!=NULL) inorder(root->right,result); } vector<int> inorderTraversal(TreeNode *root) { // write your code here vector<int> result; if(root==NULL) return result; inorder(root,result); return result; }};
方法二 非递归
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */public: vector<int> inorderTraversal(TreeNode *root) { // write your code here stack<TreeNode*> s; vector<int> result; if(root==NULL) return result; while(root!=NULL||!s.empty()){ while(root!=NULL){ s.push(root); root=root->left; } root=s.top(); s.pop(); result.push_back(root->val); root=root->right; } return result; } };
如有问题请留言。
如有帮助请顶一个,你们的支持是我最大的动力。
文章均可以转载,但请注明文章链接,谢谢。
0 0
- LintCode -- 二叉树的中序遍历
- lintcode 二叉树的中序遍历
- lintcode:二叉树的中序遍历
- lintcode,二叉树的中序遍历
- LintCode-二叉树的中序遍历
- Lintcode 二叉树的中序遍历
- Lintcode 二叉树的中序遍历
- LintCode 二叉树的中序遍历
- 二叉树的中序遍历-LintCode
- lintcode二叉树的中序遍历
- LintCode 二叉树的中序遍历
- lintcode--二叉树的中序遍历
- lintcode--二叉树的中序遍历
- lintcode-二叉树的中序遍历(非递归)-67
- Lintcode 67 二叉树的中序遍历
- lintcode——二叉树的中序遍历
- lintcode 67 二叉树的中序遍历
- LintCode 68 二叉树的中序遍历
- NOI-1000加密算法
- 版本管理工具-Git
- Intent学习笔记
- Spark算子:统计RDD分区中的元素及数量
- Postgres-XC集群部署实例(单机调试)
- Lintcode 二叉树的中序遍历
- 使用Shiro 实现登录
- 用 UltraISO 安装 Windows10 <最简单的安装方式!>
- 十道海量数据处理面试题与十个方法大总结
- 【面试题】剑指Offer-20-顺时针打印矩阵
- js杂记2 慕课网
- 蚂蚁分类信息系统 列表显示标签名称和值
- 搜狗公众号爬虫学习系列一公众号的biz
- Android 性能优化之多进程开发