力扣Leetcode 572. 另一个树的子树

另一个树的子树

给定两个非空二叉树 st,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。

示例 1:

给定的树 s:

     3
    / \
   4   5
  / \
 1   2

给定的树 t:

   4 
  / \
 1   2

返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。

示例 2:

给定的树 s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

给定的树 t:

   4
  / \
 1   2

返回 false

题解思路

双递归 暴力遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    /* 判断是否相等的函数 */
    bool isSametree(struct TreeNode* s, struct TreeNode* t){
    	if (s == NULL && t == NULL) return true;// 遍历到空时 返回true
    	return  s && t // 都不为空时依次判断
            		&& s->val == t->val  // 首先s与t的值相等
            		&& isSametree(s->left, t->left) // s t的左子树递归
            		&& isSametree(s->right, t->right); // s t的右子树递归
		}
/* 判断子树的主函数 */
bool isSubtree(struct TreeNode* s, struct TreeNode* t) {
    if (s == NULL && t == NULL) return true; // 都为空时 true
    if (s == NULL && t != NULL) return false; // s空 t非空 false
    return isSametree(s, t) // 第一种情况:s,t第一个节点就相同
        || isSubtree(s->left, t)// 第二种:t为s的左子树中一棵
        || isSubtree(s->right, t); // 第三种:t为s右子树中一课
	}
};
posted @ 2020-05-07 11:36  CoderZjz  阅读(171)  评论(0编辑  收藏  举报