[LeetCode]Binary Tree Inorder Traversal
2015-11-22 16:55
387 查看
题目描述:(链接)
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
迭代版:
递归版:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
迭代版:
/** * 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: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; stack<TreeNode *> cache; TreeNode *p = root; while (!cache.empty() || p != nullptr) { if (p != nullptr) { cache.push(p); p = p->left; } else { p = cache.top(); cache.pop(); result.push_back(p->val); p = p->right; } } return result; } };
递归版:
/** * 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: vector<int> inorderTraversal(TreeNode* root) { if (root != nullptr) { inorderTraversal(root->left); result.push_back(root->val); inorderTraversal(root->right); } return result; } private: vector<int> result; };
相关文章推荐
- ngrok服务端客户端编译
- 第十二周项目三~~图的遍历
- 拓 扑 排 序
- Jade之标签
- birt 集成 web
- maven学习1_maven的安装
- PDW命令
- php-cgi not found
- 第九章 UI布局管理器
- Android 实现滑动的几种方法(二)LayoutParams
- hihocoder 1041 国庆出游
- 1120
- 爬虫第一步:scrapy-安装教程
- 连接池及小知识点
- 三元组创建矩阵 一次定位快速转置 矩阵的加法、减法、乘法
- USACO:2.2.4 Party Lamps 派对灯
- break continue详解
- 黑马程序员 JavaSE-05 面向对象(上)
- SVN switch 用法详解
- 安卓上手-实现游戏2048