您的位置:首页 > 编程语言 > C语言/C++

leetcode 虐我篇之(十五)Binary Tree Inorder Traversal

2014-08-25 11:00 567 查看
        刚刚做完了二叉树的非递归先序遍历,现在来做做中序遍历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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息