[Leetcode] 94. Binary Tree Inorder Traversal 解题报告
来源:互联网 发布:卷皮和淘宝质量哪个好 编辑:程序博客网 时间:2024/06/01 08:50
题目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [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> inorderTraversal(TreeNode* root) { vector<int> ret; stack<TreeNode*> s; if (root == NULL) { return ret; } TreeNode *node= root; while (node) { s.push(node); node = node->left; } while (!s.empty()) { node = s.top(); s.pop(); ret.push_back(node->val); node = node->right; while (node) { s.push(node); node = node->left; } } return ret; }};
0 0
- [leetcode] 94. Binary Tree Inorder Traversal 解题报告
- LeetCode 94. Binary Tree Inorder Traversal 解题报告
- 【LeetCode】94. Binary Tree Inorder Traversal 解题报告
- Leetcode解题报告:94. Binary Tree Inorder Traversal
- LeetCode 94. Binary Tree Inorder Traversal 解题报告
- [Leetcode] 94. Binary Tree Inorder Traversal 解题报告
- [leetcode]94. Binary Tree Inorder Traversal@Java解题报告
- LeetCode(94) Binary Tree Inorder Traversal解题报告
- Leetcode 94. Binary Tree Inorder Traversal 二叉树中序遍历 解题报告
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- 【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- LeetCode(105) Construct Binary Tree from Preorder and Inorder Traversal解题报告
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal解题报告
- [leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- [Leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- linux c/c++ 面试题目整理(一)
- poj 3281 Dining 【图论-网络流-最大流-EK&Ford-Fulkerson】
- Maven—项目管理工具
- 每天一个Linux命令(58):wget
- JSESSIONID、SESSION、cookie .
- [Leetcode] 94. Binary Tree Inorder Traversal 解题报告
- angular2国际化插件
- Java编程之动态代理
- docker export和save的异同
- 代理有风险 设置需注意
- JS-Table动态增加删除行
- Docker战略结盟Rancher,提供企业级落地技术支持
- C#高效绘图(转)
- Abstract Factory(抽象工厂模式)