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?
题意:中序遍历
vector<int> InOrderTraversal(TreeNode *root) {
vector<int> path;
stack<TreeNode*> stk;
while(root != NULL || !stk.empty())
{
while(root != NULL)
{
stk.push(root);
root = root->left;
}
if( !stk.empty())
{
root = stk.top();
stk.pop();
root = root->right;
}
}
return path;
}
本文介绍了一种使用栈实现的二叉树中序遍历的迭代算法,详细解释了如何通过栈来模拟递归过程,避免了递归调用带来的额外开销。
2592

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



