zoukankan      html  css  js  c++  java
  • 力扣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右子树中一课
    	}
    };
    
  • 相关阅读:
    SUSE10 SP2/SP3 无规律死机故障解决
    随机铃声
    linux添加开机启动项
    SUSE Linux ShutdownManager issue
    linux添加开机启动项
    两个正在运行的activity之间的通信
    android 获取屏幕大小
    Linux开机启动过程分析
    grid的宽度设为100%问题
    动态处理editGridPanel
  • 原文地址:https://www.cnblogs.com/coderzjz/p/12841863.html
Copyright © 2011-2022 走看看