刚刚做完了二叉树的非递归先序遍历,现在来做做中序遍历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?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
同样的,这里是要求非迭代的方法,跟先序遍历差不多,同样是用栈来存储中间的节点。先将结点入栈,同时看是否有左结点,有的话继续将其左结点入栈,直到找到最左结点,这时候出栈并输出,同时,再对其右结点按刚才的找左结点的方式继续入栈和出栈。代码如下:
std::vector<int> inorderTraversal(TreeNode *root)
{
std::vector<int> result;
std::stack<TreeNode *> treeStack;
if (!root)
{
return result;
}
TreeNode *node = root;
//when node is not null or the stack is not empty, go loop
while(node || !treeStack.empty())
{
//find left child
while(node)
{
treeStack.push(node);
node = node->left;
}
node = treeStack.top();
result.push_back(node->val);
treeStack.pop();
node = node->right;
}
return result;
}