面试题05 - 树的子结构 [树]

先序dfs + 子判断
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");

using namespace std;
struct Node {
	int value;
	Node* lchild;
	Node* rchild;
};
bool son(Node* pr1, Node* pr2) {
	if(pr2 == NULL) return true;
	if(pr1 == NULL) return false;
	if(pr1->value != pr2->value) return false;
	return son(pr1->lchild, pr2->lchild) && son(pr1->rchild, pr2->rchild);
}
bool subTree(Node *pr1, Node *pr2) { // 先序遍历 = 先序dfs
	bool result = false;
	if(pr1 != NULL && pr2 != NULL) {
		if(pr1->value == pr2->value) {
			result = son(pr1, pr2);
		}
		if(!result) result = son(pr1->lchild, pr2);
		if(!result) result = son(pr1->rchild, pr2);
	}
	return result;
}
int main() {
	return 0;
}

posted @ 2013-01-20 19:00  小尼人00  阅读(133)  评论(0编辑  收藏  举报