Binary Tree Inorder Traversal
2015-08-10 21:21
363 查看
题目:
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?
confused what
> read more on how binary tree is serialized on OJ
思想:
对于二叉树的遍历,可以采用递归和非递归两种方式,对于递归方式,很容易求解,对于非递归方式,我们可以借助一个stack。
代码:
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?
confused what
"{1,#,2,3}"means?
> read more on how binary tree is serialized on OJ
思想:
对于二叉树的遍历,可以采用递归和非递归两种方式,对于递归方式,很容易求解,对于非递归方式,我们可以借助一个stack。
代码:
/** * Definition for a binary tree node. **/ typedef struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }*BinaryTree; class Solution { public: void CreateTree(BinaryTree & T)//二叉树的建立 { char data; cin >> data; if (data == '#' ) T == NULL; else { T = new TreeNode(data-'0'); CreateTree(T->left); CreateTree(T->right); } } void inorder(TreeNode*root, vector<int>&ret) { if (root != NULL) { inorder(root->left,ret); ret.push_back(root->val); inorder(root->right,ret); } } vector<int> inorderTraversal(TreeNode* root) {//递归 vector<int> ret; inorder(root, ret); return ret; } vector<int> inorderTraversal2(TreeNode *root)//非递归 { stack<TreeNode *> s; TreeNode *p = root; vector<int> ret; while (p!=NULL || !s.empty()) { while (p != NULL) { s.push(p); p = p->left; } if (!s.empty()) { p = s.top(); s.pop(); ret.push_back(p->val); p = p->right; } } return ret; } };
相关文章推荐
- C#里怎样把一个DataTable的数据追加进数据库里的某个表
- 数学分析 + 容斥原理 - URAL 1907 Coffee and Buns
- CodeForces 4D-Mysterious Present
- poj 3274 Gold Balanced Lineup
- js中的简单排序
- 黑马程序员——类与对象
- Android中JNI的使用方法
- JavaScript 知识点总结-3
- Eclipse --- 常用配置及快捷键
- POJ 3261 Milk Patterns 可重复k次的最长重复子串
- 根据字符分割字符串
- Hibernate学习笔记(五) — 多对多关系映射
- 面试官的技术面试技巧与步骤
- 考试
- Borg Maze【POJ--3026】【并查集】
- 产品项目生命周期中的各种文档
- 115个Java面试题和答案——终极列表(上)
- [2015hdu多校联赛补题]hdu5302 Connect the Graph
- 一些项目需要的东西整合(1)——九款按钮
- 用过滤器解决全站中文数据提交乱码问题