22.从上往下打印二叉树
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> vec;
queue<TreeNode*> que;
if (root == NULL)
return vec;
que.push(root);
while (!que.empty())
{
TreeNode *tmp = que.front();
vec.push_back(tmp->val);
que.pop();
if (tmp->left != NULL)
que.push(tmp->left);
if (tmp->right != NULL)
que.push(tmp->right);
}
return vec;
}
23.二叉搜索树的后序遍历序列
#include <iostream>
#include <vector>
using namespace std;
bool getSequence(vector<int> sequence, int left, int right)
{
if (left >= right)
return true;
int mid = 0;
for (int i = 0; i < right; i++)
{
if (sequence[i] > sequence[right])
{
mid = i;
break;
}
mid++;
}
for (int i = mid; i < right; i++)
{
if (sequence[i] < sequence[right])
return false;
}
return getSequence(sequence, left, mid - 1) && getSequence(sequence, mid, right - 1);
}
bool VerifySquenceOfBST(vector<int> sequence) {
if (sequence.empty())
return false;
int left = 0, right = sequence.size() - 1;
return getSequence(sequence, left, right);
}
int main()
{
int a[] = { 4,6,7,5 };
vector<int> vec(a, a + 4);
bool l = VerifySquenceOfBST(vec);
cout << l << endl;
system("pause");
return 0;
}
24.二叉树中和为某一值的路径
class Solution {
public:
void getPath(TreeNode *root, int expectNumber, int now, vector<int> &vec, vector<vector<int> > &res)
{
if (root != NULL)
{
now += root->val;
vec.push_back(root->val);
if (now == expectNumber && root->left == NULL && root->right == NULL)
{
res.push_back(vec);
vec.pop_back();
return;
}
if (root->left != NULL)
getPath(root->left, expectNumber, now, vec, res);
if (root->right != NULL)
getPath(root->right, expectNumber, now, vec, res);
vec.pop_back();
}
}
vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
vector<vector<int> > res;
vector<int> vec;
if (root == NULL)
return res;
int num = 0;
getPath(root, expectNumber, num, vec, res);
return res;
}
};