[sword finger offer{23-24}] post order traversal sequence of binary search tree, path with a certain value in binary tree
Posted by ~n[EO]n~ on Thu, 19 Dec 2019 23:28:15 +0100
The path of the binary search tree with a certain value in the sequence of subsequent traversal, binary tree and neutralization
Post order traversal sequence of binary search tree
Title Description
- Input an integer array to determine whether the array is the result of the subsequent traversal of a binary search tree. If Yes, output Yes; otherwise, output No. Suppose that any two numbers of the input array are different from each other.
C++ code
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence)
{
if(sequence.size()==0)
{
return false;
}
else
{
int len = sequence.size();
vector<int>left,right;
int i = 0;
for(;i<len-1;i++)
{
if(sequence[i]<sequence[len-1])
{
left.push_back(sequence[i]);
}
else
{
break;
}
}
for(;i<len-1;i++)
{
if(sequence[i]>sequence[len-1])
{
right.push_back(sequence[i]);
}
else
{
return false;
}
}
bool L = true;
bool R = true;
if(left.size()!=0)
{
L = VerifySquenceOfBST(left);
}
if(right.size()!=0)
{
R = VerifySquenceOfBST(right);
}
return L && R;
}
}
};
Path with a certain value in a binary tree
Title Description
- Input the following node and an integer of a binary tree, and print out all paths in which the sum of node values in the binary tree is the input integer. Path is defined as a path from the root node of the tree to the node that the leaf node passes through. (Note: in the list of returned values, the array with large array length is first)
C++ code
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber)
{
vector<vector<int>>res;
vector<int>out;
helper(root,expectNumber,out,res);
return res;
}
void helper(TreeNode*node,int sum,vector<int>&out,vector<vector<int>>&res)
{
if(node==NULL)
{
return;
}
out.push_back(node->val);
if(sum==node->val && node->left==NULL && node->right==NULL)
{
res.push_back(out);
}
helper(node->left,sum-node->val,out,res);
helper(node->right,sum-node->val,out,res);
out.pop_back();
}
};