堆栈非递归实现
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
TreeNode* p;
vector<vector<int>> result;
if(root==NULL)
return result;
queue<TreeNode*> q;
q.push(root);
vector<int> level;
while(!q.empty()){
int size;
size=q.size();
for(int i=0;i<size;i++){
p=q.front();
q.pop();
level.push_back(p->val);
if(p->left){
q.push(p->left);
}
if(p->right){
q.push(p->right);
}
}
result.push(level);
vector<int>
}
return result;
}
};
递归实现
class Solution {
public:
vector<int> result;
vector<int> inorderTraversal(TreeNode* root) {
if(root){
inorderTraversal(root->left);
result.push_back(root->val);
inorderTraversal(root->right);
}
return result;
}
};