标签:
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
二叉树的中序遍历非递归实现,悲催的是只知道需要使用栈来实现,但是具体的代码如何编写却忘记了。函数调用是通过栈来实现的,所以之前使用递归来实现的中序遍历可以转用非递归来实现。
具体的分析可以参考这篇博客。
runtime:0ms
/**
* 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> res;
if(root==NULL)
return res;
TreeNode *node=root;
stack<TreeNode*> s;
while(!s.empty()||node)
{
while(node)
{
s.push(node);
node=node->left;
}
node=s.top();
s.pop();
res.push_back(node->val);
node=node->right;
}
return res;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode94:Binary Tree Inorder Traversal
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/46873565