剑指offer 树的子结构

剑指offer 树的子结构

  • 题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

  • 题目解析

本题用递归地方法来求解。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    bool hasSub(TreeNode* p1, TreeNode* p2){
		if (p2 == NULL)
			return true;
		if (p1 == NULL)
			return false;
		if (p1->val != p2->val)
			return false;
		return hasSub(p1->left, p2->left) && hasSub(p1->right, p2->right);
	}

	bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
	{
		if (pRoot2 == NULL || pRoot1==NULL)
			return false;
		else{
			bool ret = false;
			if (pRoot1->val == pRoot2->val)
				ret = hasSub(pRoot1, pRoot2);
			if (ret != true)
				ret = hasSub(pRoot1->left, pRoot2);
			if (ret != true)
				ret = hasSub(pRoot1->right, pRoot2);
			return ret;
		}
	}
};
弹钢琴的猫 /
Published under (CC) BY-NC-SA in categories 算法  tagged with 剑指offer  Tree