leetcode 虐我篇之(十五)Binary Tree Inorder Traversal
来源:互联网 发布:qq购物号网络名称 编辑:程序博客网 时间:2024/05/07 00:54
刚刚做完了二叉树的非递归先序遍历,现在来做做中序遍历Binary Tree Inorder Traversal,题目描述如下:
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?confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.同样的,这里是要求非迭代的方法,跟先序遍历差不多,同样是用栈来存储中间的节点。先将结点入栈,同时看是否有左结点,有的话继续将其左结点入栈,直到找到最左结点,这时候出栈并输出,同时,再对其右结点按刚才的找左结点的方式继续入栈和出栈。代码如下:
std::vector<int> inorderTraversal(TreeNode *root){std::vector<int> result;std::stack<TreeNode *> treeStack;if (!root){return result;}TreeNode *node = root;//when node is not null or the stack is not empty, go loopwhile(node || !treeStack.empty()){//find left childwhile(node){treeStack.push(node);node = node->left;}node = treeStack.top();result.push_back(node->val);treeStack.pop();node = node->right;}return result;}
0 0
- leetcode 虐我篇之(十五)Binary Tree Inorder Traversal
- LeetCode 之 Binary Tree Inorder Traversal
- LeetCode之Binary Tree Inorder Traversal
- LeetCode之Binary Tree Inorder Traversal
- leetcode之Binary Tree Inorder Traversal
- LeetCode: Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- LeetCode : Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- 【leetcode】Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- [leetcode]Binary Tree Inorder Traversal
- LeetCode-Binary Tree Inorder Traversal
- 人活一次,不做蝼蚁!
- Linux软链接和硬链接
- Spark上矩阵运算库(六)——高级矩阵操作2
- 冒泡、选择、快速排序算法(附java实现源码)
- TCP三次握手及四次挥手详细图解
- leetcode 虐我篇之(十五)Binary Tree Inorder Traversal
- 系统吞度量评估
- eclipse下看android support v4源码
- CountDownTimer 验证码发送后显示倒计时
- mac上打开chm文件
- Java读取properties文件
- 国外的讲解container_of() 很透彻,值得一看
- [BestCoder Round #6] hdu 4981 Goffi and Median (水题)
- Android Android Unable to resolve target 'android-19' 问题