您的位置:首页 > 其它

[Leetcode]Binary Tree Inorder Traversal

2015-09-22 11:44 471 查看
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?

class Solution {
public:
/*algorithm: recuisvie
*/
void inorderSub(TreeNode* root,vector<int>&path){
if(!root)return;
inorderSub(root->left,path);
path.push_back(root->val);
inorderSub(root->right,path);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int>path;
inorderSub(root,path);
return path;
}
};
class Solution {
public:
/*algorithm: iterative
*/
vector<int> inorderTraversal(TreeNode* root) {
vector<int>path;
if(!root)return path;
stack<TreeNode*>stk;
unordered_set<TreeNode*>S;
stk.push(root);
while(!stk.empty()){
TreeNode* t = stk.top();
while(t->left && !S.count(t->left)){
stk.push(t->left);
S.insert(t->left);
t = t->left;
}
path.push_back(t->val);
stk.pop();
if(t->right)stk.push(t->right);
}
return path;

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