zoukankan      html  css  js  c++  java
  • 剑指offer(13)

    题目:

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

    思路:

      判断当前两个根结点是否相等,如果相等,判断左右子树是否相等,如果不依次判断左右子树是否满足上面所述条件。

      为了便于表示,这里采用递归的方式:

    /**
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    */
    public class Solution {
        public boolean HasSubtree(TreeNode root1,TreeNode root2) {
            boolean result = false;
            
            if(root1!=null&&root2!=null){
                if(root1.val==root2.val){
                    result = DoesTree1HaveTree2(root1,root2);
                }
                if(!result){
                    result = HasSubtree(root1.left,root2);
                }
                if(!result){
                    result = HasSubtree(root1.right,root2);
                }
            }
            return result;
        }
        
        private boolean DoesTree1HaveTree2(TreeNode root1,TreeNode root2){
        //这里要注意两个判断的顺序,必须显示root2判断在前,因为如果2树为空则表示这一支树符合题意,如果把root1条件放前,就会导致明明一条支树判断应当结束,却依然进行的情况 if(root2==null){ return true; } if(root1==null) return false; if(root1.val!=root2.val){ return false; } return DoesTree1HaveTree2(root1.left,root2.left)&&DoesTree1HaveTree2(root1.right,root2.right); } }

      

  • 相关阅读:
    基于FPGA的ARP协议实现
    Modelsim 仿真错误集锦
    基于FPGA的IIC驱动设计
    状态机跑飞的解决办法
    基于FPGA的检测时钟脉冲的高电平及低电平的中点标志位设计
    基于FPGA的UART实现
    基于FPGA的数字秒表设计
    Matlab的常用调试方法
    基于FPGA的花样流水灯
    **time_limited.sof文件
  • 原文地址:https://www.cnblogs.com/figsprite/p/10470797.html
Copyright © 2011-2022 走看看