Binary Tree Inorder Traversal
来源:互联网 发布:字体管家mac版 编辑:程序博客网 时间:2024/05/01 15:50
题目:
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;}};
0 0
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- 【算法笔记】Aho-Corasick 算法(AC自动机) 小结
- Android 编程下的 EditView 阻止软键盘自动弹出__图片资源文件后缀不能为.ico
- 约瑟夫环问题 循环链表
- MapReduce的处理流程(一)
- 用过滤器解决全站中文数据提交乱码问题
- Binary Tree Inorder Traversal
- [ACM] HDU 1242 Rescue (优先队列)
- poj 3274 Gold Balanced Lineup
- JavaScript 知识点总结-3
- Android中JNI的使用方法
- 类和对象
- Eclipse --- 常用配置及快捷键
- 黑马程序员——类与对象
- C++基础---有返回值类型函数(返回非引用类型)