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
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
思路:
对每个node做一个记号。第一次碰到的时候,先进入其左子树。第二次碰到的时候,访问该结点。
题解:
/**
* Definition for binary tree
* 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) {
if (root == nullptr)
return vector<int>();
vector<int> result;
// the bool states if its left leaf is visited already
list<pair<TreeNode*, bool>> nodes;
nodes.push_back(make_pair(root, false));
while(!nodes.empty())
{
auto& front = nodes.front();
if (front.second == false)
{
// its left node has not visited
front.second = true;
if (front.first->right != nullptr)
nodes.insert(next(begin(nodes)), make_pair(front.first->right, false));
if (front.first->left != nullptr)
nodes.push_front(make_pair(front.first->left, false));
continue;
}
else
{
result.push_back(front.first->val);
nodes.pop_front();
}
}
return result;
}
};
本文介绍了一种二叉树中序遍历的迭代方法,通过使用链表记录节点状态,实现了不依赖递归的遍历过程。
727

被折叠的 条评论
为什么被折叠?



