1. 程式人生 > >二叉樹 判斷一棵樹是否是另一棵樹的子樹

二叉樹 判斷一棵樹是否是另一棵樹的子樹

題目:判斷判斷一棵樹是否是另一棵樹的子樹,子樹的意思是隻要包含了一個結點,就得包含這個結點下的所有節點。意思就是二叉樹結點的值也要相等 如下圖2就是1的子樹 如果將第二顆樹根節點右孩子data改為2 就不是子樹了。
思路:將二叉樹序列化,轉化為2個字串,再利用kmp演算法或stl中的find()函式即可,若結點為空用#代表data 二樹先序序列化為 1_#8_7##9##_ 用"_"表示一個結點結束符
在這裡插入圖片描述

#include <iostream>
#include <string>
using namespace std;
struct btnode {
	int data;
	struct btnode* lchild;
	struct btnode* rchild;
};
//建立二叉樹
void create_btree(btnode* &T){
	T = new btnode;
	T->lchild = NULL;
	T->rchild = NULL;
	int a;
	cin >> a;
	if (a == -1) {
		T = NULL;
		return;
	}
	else {
		T->data = a;
		create_btree(T->lchild);
		create_btree(T->rchild);
	}
}
//二叉樹轉化為string  中序序列化 也可以先序 後序
void btree_to_str(const btnode* T, string& s) {
	if (T) {
		btree_to_str(T->lchild, s);
		s += to_string(T->data);
		s += "_";//每個結點後加 _ 以分割相鄰結點 
		btree_to_str(T->rchild, s);
	}
}
int main()
{
	string s1, s2;
	btnode *T1, *T2;
	create_btree(T1);
	create_btree(T2);
	btree_to_str(T1, s1);
	btree_to_str(T2, s2);

	cout <<"s1="<< s1<<"     s2="<<s2<<endl;
	if ( s1.find(s2) != -1) {
		cout << "是子樹";
	}
	else {
		cout << "不是子樹";
	}
	return 0;
}

在這裡插入圖片描述