zoukankan      html  css  js  c++  java
  • 判断二叉树之间的子树关系

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

     1 package com.algorithm;
     2 
     3 /*class TreeNode {
     4  int val = 0;
     5  TreeNode left = null;
     6  TreeNode right = null;
     7  public TreeNode(int val) {
     8  this.val = val;
     9  }
    10  }*/
    11 public class HasSubtreeTest {
    12     class TreeNode {
    13         int val = 0;
    14         TreeNode left = null;
    15         TreeNode right = null;
    16 
    17         public TreeNode(int val) {
    18             this.val = val;
    19         }
    20     }
    21 
    22     public boolean HasSubtree(TreeNode root1, TreeNode root2) {
    23         boolean result = false;// 返回结果
    24         if (root1 != null && root2 != null) {
    25             if (root1.val == root2.val)
    26                 result = IsTree1HasTree2(root1, root2);// 递归遍历
    27             if (!result) // 如果根结点不行,那么继续向左右子树遍历
    28                 result = IsTree1HasTree2(root1.left, root2);
    29             if (!result)
    30                 result = IsTree1HasTree2(root1.right, root2);
    31         }
    32         return result;
    33     }
    34 
    35     public boolean IsTree1HasTree2(TreeNode root1, TreeNode root2) {
    36         // 如果root1 为空 并且 root2不为空,那么代表并没有找到
    37         if (root1 == null && root2 != null)
    38             return false;
    39         // 如果根2 为空 ,则代表当前结点有
    40         if (root2 == null)
    41             return true;
    42         // 如果结点值不相等,那么返回false
    43         if (root1.val != root2.val)
    44             return false;
    45         // 再左右遍历子树
    46         return IsTree1HasTree2(root1.left, root2.left)
    47                 && IsTree1HasTree2(root1.right, root2.right);
    48     }
    49 
    50     public static void main(String[] args) {
    51 
    52     }
    53 }
  • 相关阅读:
    习题8-8 判断回文字符串
    Field笔记
    Object类中的方法
    字符和字节的区别
    Layui搜索设置每次从第一页开始
    Springboot+Jpa+Layui使用Pageable工具进行数据分页
    Map<String, Object>返回类型
    List集合中剔除重复的数据
    Springboot+Mybatis(Mysql 、Oracle) 注解和使用Xml两种方式批量添加数据
    MySql中group_concat函数的使用
  • 原文地址:https://www.cnblogs.com/fankongkong/p/6519429.html
Copyright © 2011-2022 走看看