您的位置:首页 > 其它

二叉树的中序遍历

2015-08-25 00:06 225 查看
给出一棵二叉树,返回其中序遍历

样例

给出二叉树
{1,#,2,3}
,
1
\
2
/
3

返回
[1,3,2]
.

/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<int> result;
if (root == NULL)
{
return result;
}

stack<TreeNode*> values;
values.push(root);
TreeNode *last = NULL;
while (!values.empty())
{
TreeNode *top = values.top();
if (top->left != NULL)
{
if (top->left == last)
{
result.push_back(top->val);
values.pop();
last = top;
if (top->right != NULL)
{
values.push(top->right);
}
}
else
{
values.push(top->left);
}
}
else
{
result.push_back(top->val);
values.pop();
last = top;
if (top->right != NULL)
{
values.push(top->right);
}
}
}

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