二叉树层序遍历
class Solution {
public:
queue<TreeNode*> ready;
vector<vector<int>> res;
vector<vector<int>> levelOrder(TreeNode* root) {
if(!root)
{
return res;
}
ready.push(root);
while(!ready.empty())
{
int centerSize = ready.size();
vector<int> temp;
for(int i =0;i<centerSize;i++)
{
auto center = ready.front();
ready.pop();
temp.push_back(center->val);
if(center->left)
{
ready.push(center->left);
}
if(center->right)
{
ready.push(center->right);
}
}
res.push_back(temp);
}
return res;
}
};
二叉树中序遍历
class Solution {
public:
vector<int> res;
int mid(TreeNode* node)
{
if(node == nullptr)
return 0;
mid(node->left);
res.push_back(node->val);
mid(node->right);
return 0;
};
vector<int> inorderTraversal(TreeNode* root) {
mid(root);
return res;
}
};
二叉树后续遍历
迭代版本
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> res;
if(root == NULL)
return res;
TreeNode* pre = NULL;
while(root!=NULL||!s.empty())
{
while(root!= NULL)
{
s.push(root);
root = root->left;
}
root = s.top();
if(root->right!= NULL&&root->right!= pre)
{
root = root->right;
}
else
{
pre = root;
res.push_back(root->val);
s.pop();
root = NULL;
}
}
return res;
}
};
二叉树前序遍历
class Solution {
public:
vector<int> res;
void cersion(TreeNode* root)
{
if(!root)
{
return;
}
res.push_back(root->val);
cersion(root->left);
cersion(root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
cersion(root);
return res;
}
};
前序中序生成二叉树
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
this->preorder = preorder;
for(int i = 0; i < inorder.size(); i++)
dic[inorder[i]] = i;
return recur(0, 0, inorder.size() - 1);
}
private:
vector<int> preorder;
unordered_map<int, int> dic;
TreeNode* recur(int root, int left, int right) {
if(left > right) return nullptr;
TreeNode* node = new TreeNode(preorder[root]);
int i = dic[preorder[root]];
node->left = recur(root + 1, left, i - 1);
node->right = recur(root + i - left + 1, i + 1, right);
return node;
}
};
二叉搜索树后序遍历
class Solution {
public:
unordered_map<int,int>map;
vector<int> postorder;
bool recurser(int root,int left,int right,vector<int> &inOrder)
{
if(root<0)
return true;
int i = map[postorder[root]];
int rightNum = right - i;
int leftNum = i-left;
if(left >= right)
return true;
for(int j = root-1;j>(root-rightNum);j--)
{
if(postorder[j]<postorder[root])
return false;
}
for(int j = (root-rightNum-1);j>root-rightNum-1-leftNum;j--)
{
if(postorder[j]>postorder[root])
return false;
}
return recurser(root-1,i+1,right,inOrder)&&recurser(root - rightNum-1,left,i-1,inOrder);
}
bool verifyPostorder(vector<int>& postorder) {
this->postorder =postorder;
int size = postorder.size();
vector<int> inOrder = postorder;
sort(inOrder.begin(),inOrder.end());
for(int i = 0;i<size;i++)
{
map[inOrder[i]] = i;
}
return recurser(size-1,0,size-1,inOrder);
}
};
|