您的位置:首页 > 其它

Binary Tree Inorder Traversal

2015-08-10 21:21 363 查看
题目:

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

思想:

对于二叉树的遍历,可以采用递归和非递归两种方式,对于递归方式,很容易求解,对于非递归方式,我们可以借助一个stack。

代码:

/**
* Definition for a binary tree node.
**/
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}*BinaryTree;

class Solution {
public:
void CreateTree(BinaryTree & T)//二叉树的建立
{
char data;
cin >> data;

if (data == '#' )
T == NULL;
else
{
T = new TreeNode(data-'0');
CreateTree(T->left);
CreateTree(T->right);
}
}

void inorder(TreeNode*root, vector<int>&ret)
{
if (root != NULL)
{
inorder(root->left,ret);
ret.push_back(root->val);
inorder(root->right,ret);
}
}

vector<int> inorderTraversal(TreeNode* root) {//递归
vector<int> ret;
inorder(root, ret);
return ret;
}

vector<int> inorderTraversal2(TreeNode *root)//非递归
{
stack<TreeNode *> s;
TreeNode *p = root;
vector<int> ret;
while (p!=NULL || !s.empty())
{

while (p != NULL)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
s.pop();
ret.push_back(p->val);
p = p->right;
}
}
return ret;
}

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