题目33分析:(二叉搜索树的后续遍历序列)
根据二叉搜索树的特点判断后序遍历的序列是否满足条件思路:
1.后序遍历序列的最后一个元素是根节点
2.左子树的所有节点都小于根节点
3.右子树的所有节点都大于根节点
4.递归判断左子树是否是搜索二叉树,直至叶子节点
5.递归判断右子树是否是搜索二叉树,直至叶子节点
#include <iostream>
using namespace std;
bool is_sequence_of_BST(int sequence[], int length)
{
if (sequence == NULL || length < 1)
return false;
//1.后序遍历序列的最后一个元素是根节点
int root = sequence[length - 1];
//2.左子树的所有节点都小于根节点
int i = 0;
for (; i < length - 1; i++)
{
if (sequence[i] > root)
break;
}
//3.右子树的所有节点都大于根节点
int j = i;
for (; j < length - 1; j++)
{
if (sequence[j] < root)
return false;
}
//4.递归判断左子树是否是搜索二叉树,直至叶子节点
bool left_sub_tree = true;
if (i > 0)
left_sub_tree = is_sequence_of_BST(sequence, i);
//5.递归判断右子树是否是搜索二叉树,直至叶子节点
bool right_sub_tree = true;
if(j>0)
right_sub_tree = is_sequence_of_BST(sequence+i, length-i-1);
return(left_sub_tree&&right_sub_tree);
}
void main()
{
int sequence[] = { 5,7,6,9,11,10,8 };
int length = sizeof(sequence) / sizeof(sequence[0]);
if (is_sequence_of_BST(sequence, length))
cout << "OK!!!" << endl;
}
题目34分析:(二叉树中路径上的节点之和为某值)
利用前序遍历,将当前遍历的节点压入栈中,直至叶子节点计算此路径之和,若满足某值则打印,然后删除栈中的此叶子节点,返回上级递归继续遍历。
思路:
1.累加递归过程中的节点值,直至叶子节点
2.前序遍历将结点压入栈中
3.判断当前遍历节点是否为叶子节点,若为叶子节点则判断是否满足某值,然后打印当前栈
4.如果不是叶子节点,继续前序遍历递归
5.从叶子节点返回父节点时,删除栈中的叶子节点
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct BTNode
{
int data;
BTNode *lchild;
BTNode *rchild;
};
BTNode * create_binary_tree(int level, string pos)
{
cout << "输出 " << level << " 层 " << pos << endl;
int data;
cin >> data;
if (data == 0)
return NULL;
BTNode *new_node = new BTNode;
new_node->data = data;
new_node->lchild = create_binary_tree(level+1, "lchild");
new_node->rchild = create_binary_tree(level+1, "rchild");
return new_node;
}
void print_binary_tree(BTNode *node)
{
if(node)
{
cout << node->data << " ";
print_binary_tree(node->lchild);
print_binary_tree(node->rchild);
}
}
void find_path_of_value(BTNode *node, int value, vector<int> path, int cur_value)
{
//1.累加递归过程中的节点值,直至叶子节点
cur_value += node->data;
cout << "当前路径的值:" << cur_value << endl;
//2.前序遍历将结点压入栈中
path.push_back(node->data);
//3.判断当前遍历节点是否为叶子节点,若为叶子节点则判断是否满足某值,然后打印当前栈
bool is_leaf = node->lchild == NULL&&node->rchild == NULL;
if (cur_value == value&&is_leaf)
{
cout << "满足条件的路径:";
vector<int>::iterator begin = path.begin();
while (begin != path.end())
{
cout << *begin << " ";
begin++;
}
cout << endl;
}
//4.如果不是叶子节点,继续前序遍历递归
if (node->lchild != NULL)
{
find_path_of_value(node->lchild, value, path, cur_value);
}
if (node->rchild != NULL)
{
find_path_of_value(node->rchild, value, path, cur_value);
}
//5.从叶子节点返回父节点时,删除栈中的叶子节点值
path.pop_back();
}
void main()
{
BTNode *tree = new BTNode;
tree = create_binary_tree(1, "root");
print_binary_tree(tree);
int value = 22, cur_value = 0;
vector<int> path;
find_path_of_value(tree, value, path, cur_value);
}