94. Binary Tree Inorder Traversal
来源:互联网 发布:java mvc框架 编辑:程序博客网 时间:2024/06/05 09:46
1、题目描述
输入一个二叉树,返回它的中序遍历。
2、思路
way 1: Recursive Solution
way 2:Iterative Solution
声明一个stack,把根节点放进去,把根节点的左节点放入,循环这个过程,知道左节点是NULL。
把stack顶的节点root取出,把节点数值放入ans,若root的右节点非NULL,把右节点放入stack,把右节点的左节点放入stack,
循环这个过程。
重复上述过程,直到stack为空。
3、代码
递归法:略。
vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; stack<TreeNode*> s; while(root){ s.push(root); root = root->left; } while(!s.empty()){ root = s.top(); s.pop(); ans.push_back(root->val); if(root->right){ root = root->right; while(root){ s.push(root); root = root->left; } } } return ans; } /*vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; stack<TreeNode*> s; while(root||!s.empty()){ if(root){ s.push(root); root=root->left; } else{ root = s.top(); s.pop(); ans.push_back(root->val); root=root->right; } } return ans; }*/
阅读全文
0 0
- 94. Binary Tree Inorder Traversal
- 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 如何改变Redis用不好的误区
- Caffe中convert_imageset的用法解释
- Postgresql快速写入/读取大量数据(.net)
- hadoop生态系统软件版本匹配
- 通过 GitBook 开源框架和 GitHub 私有化部署 Wiki 文档
- 94. Binary Tree Inorder Traversal
- python 与浏览器接口换行问题
- 制作login.jsp页面,要求实现提供用户登陆的界面, 用户通过该界面输入用户名(控件名userName)和密码(控件名password), 然后点击“登录”按钮实现登陆操作.
- redis 删除key下特定内容
- 秒杀多线程第七篇 经典线程同步 互斥量Mutex
- Ubuntu下搭建Git服务器
- SpringBoot入门-10(springboot配置freemarker模板)
- TextInputLayout的使用
- 自动释放linux内存