• 【二叉树】树的子结构


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

     1 /**
     2 public class TreeNode {
     3     int val = 0;
     4     TreeNode left = null;
     5     TreeNode right = null;
     6 
     7     public TreeNode(int val) {
     8         this.val = val;
     9 
    10     }
    11 
    12 }
    13 */
    14 public class Solution {
    15     public boolean HasSubtree(TreeNode root1,TreeNode root2) {
    16 
    17          boolean result = false;
    18          
    19          if(root1 != null && root2 != null){
    20              
    21              if(root1.val == root2.val){
    22                  result = DoesTree1HasTree2(root1,root2);
    23              }
    24              
    25             //递归遍历左子树 
    26             if(!result){
    27                 result = HasSubtree(root1.left, root2);
    28             }
    29             
    30             //递归遍历右子树
    31             if(!result){
    32                 result = HasSubtree(root1.right, root2);
    33             }
    34          }
    35         
    36         return result;
    37     
    38     }
    39     
    40     
    41     public boolean DoesTree1HasTree2(TreeNode root1,TreeNode root2){
    42         
    43         if(root2 == null){
    44             return true;
    45         }
    46         
    47         if(root1 == null){
    48             return false;
    49         }
    50         
    51         if(root1.val != root2.val){
    52             return false;
    53         }
    54         
    55         return DoesTree1HasTree2(root1.left, root2.left) && DoesTree1HasTree2(root1.right, root2.right);
    56     }
    57 }
  • 相关阅读:
    看看优酷是怎么做网络投票的?
    CURL的学习和应用
    PHP生成word的三种方式
    感谢
    网站后台权限设计
    ORACLE 11g 导出数据
    第一份blog
    查看tomcat的内存情况
    执行sshadd时出现Could not open a connection to your authentication agent
    读取SSDT当前函数地址
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/5878799.html
Copyright © 2020-2023  润新知