LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
来源:互联网 发布:usb摄像头拍照软件 编辑:程序博客网 时间:2024/05/10 10:52
翻译
给定一个二叉树,返回其中序遍历的节点的值。例如:给定二叉树为 {1, #, 2, 3} 1 \ 2 / 3返回 [1, 3, 2]备注:用递归是微不足道的,你可以用迭代来完成它吗?
原文
Given a binary tree, return the inorder traversal of its nodes' values.For example:Given binary tree {1,#,2,3}, 1 \ 2 / 3return [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> v; vector<int> inorderTraversal(TreeNode* root) { if (root != NULL) { inorderTraversal(root->left); v.push_back(root->val); inorderTraversal(root->right); } return v; }};
接下是是时候写成迭代咯~
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*> tempStack; while (!tempStack.empty() || root != NULL) { if (root != NULL) { tempStack.push(root); root = root->left; } else { root = tempStack.top(); result.push_back((tempStack.top())->val); tempStack.pop(); root = root->right; } } return result; }};
另有两道类似的题目:
LeetCode 144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)
LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)
2 0
- LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
- LeetCode | Binary Tree Inorder Traversal(二叉树的中序遍历)
- LeetCode OJ 之 Binary Tree Inorder Traversal (二叉树的中序遍历)
- LeetCode 94. Binary Tree Inorder Traversal(二叉树的中序遍历)
- LeetCode Binary Tree Inorder Traversal 中序遍历二叉树
- Binary Tree Inorder Traversal 二叉树的中序遍历
- 二叉树的中序遍历 Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal 二叉树的中序遍历
- 94.LeetCode Binary Tree Inorder Traversal(medium)[中序遍历二叉树 树的遍历]
- LeetCode 144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)
- LeetCode 94 Binary Tree Inorder Traversal(二叉树中序遍历)
- LintCode Binary Tree Inorder Traversal 二叉树的中序遍历(非递归)
- Binary Tree Inorder Traversal 二叉树的中序遍历(迭代非递归版本)
- 67.Binary Tree Inorder Traversal-二叉树的中序遍历(容易题)
- LeetCode—***Binary Tree Inorder Traversal二叉树的中序遍历
- [LeetCode]94. Binary Tree Inorder Traversal--二叉树的中序遍历
- 【LeetCode】Binary Tree Inorder Traversal二叉树的中序遍历
- 【leetcode】94Binary Tree Inorder Traversal(非递归中序遍历二叉树)
- UESTC 485 Game(康托展开,bfs打表)
- 数据库丢失后的紧急注意事项
- 20160224.CCPP体系详解(0034天)
- Ajax的工作原理分析
- CodeForces 596A
- LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
- 指针与数组不同的存储区域
- 全排列
- win7中安装jdk/mysql/odbc
- stl算法设计理念:函数对象和函数对象当参数和返回值
- 关于Fibonacci算法及Lucas算法说明
- 一种用于解决银行代理产品交易热点账户的系统及方法
- GitHub: 终端上传项目
- tomcat日志文件目录修改