您的位置:首页 > 其它

LeetCode之Binary Tree Inorder Traversal

2015-08-05 15:59 399 查看
/*方法一:递归中序遍历。*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}

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

/*方法二:利用栈,迭代法中序遍历*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
stack<TreeNode*> s;
TreeNode *p = root;
while(!s.empty() || p != nullptr){
if(p != nullptr){
s.push(p);
p = p->left;
}
else{
p = s.top();
s.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: