新手最近开始刷Leetcode,将提交的代码做个简单记录。
先序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> myStack;
vector<int> value;
if(!root)
return value;
while(root||!myStack.empty())
{
if(root)
{
myStack.push(root);
value.push_back(root->val);
root=root->left;
}
else
{
root=myStack.top();
root=root->right;
myStack.pop();
}
}
return value;
}
};
中序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> myStack;
vector<int> value;
if(!root)
return value;
while(root||!myStack.empty())
{
if(root)
{
myStack.push(root);
root=root->left;
}
else
{
root=myStack.top();
value.push_back(root->val);
myStack.pop();
root=root->right;
}
}
return value;
}
};
层序遍历(102)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> mynode;
vector<vector<int>> myvalue;
vector<int> value;
TreeNode* p=root;
if(!root) return {};
mynode.push(p);
int count=1;
while(!mynode.empty())
{
p=mynode.front();
value.push_back(p->val);
mynode.pop();
count--;
if(p->left) mynode.push(p->left);
if(p->right) mynode.push(p->right);
if(!count)
{
myvalue.push_back(value);
value.clear();
count+=mynode.size();
}
}
return myvalue;
}
};