zoukankan      html  css  js  c++  java
  • JZ17 树的子结构

    题目描述

    输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
     
    这题分两步:
      第1:在树A中找到和树B的根节点的值一样的节点R,注意树的节点值可以有多个相同的值。
      第2:判断树A中以R为根节点的子树是不是包含和B一样的树结构。
    这题难在递归基和判断树节点为空该返回什么,一定要记清楚找头结点的时候遇到空节点就返回错,helper函数如果子树为空,还有就是result的使用。
    说明已经匹配完了,返回true;如果是树A为空,说明匹配不到子树,返回false。
     
    理解难点:helper每次返回以该根节点开始的是否匹配,然后判断左子树和右子树是否匹配。
     
    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    
    func helper( pRoot1 *TreeNode ,  pRoot2 *TreeNode ) bool {
        if pRoot2 == nil {
            return true
        }
        if pRoot1 == nil {
            return false
        }
        if pRoot1.Val != pRoot2.Val {
            return false
        }
        return helper(pRoot1.Left, pRoot2.Left) && helper(pRoot1.Right, pRoot2.Right)
    }
    
    func isSubStructure( pRoot1 *TreeNode ,  pRoot2 *TreeNode ) bool {
        // write code here
        if pRoot1 == nil || pRoot2 == nil {
            return false
        }
     
        return helper(pRoot1, pRoot2) || isSubStructure(pRoot1.Left, pRoot2) || isSubStructure(pRoot1.Right, pRoot2)
    }
  • 相关阅读:
    C# using
    Spring框架
    is
    pycharm破解197
    python安装197
    python3.7.0安装197
    centos7 minimal 安装mysql197
    centos7 minimal 安装 &网络配置197
    ruby安装卸载197
    redis安装 卸载 启动 关闭197
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/14630406.html
Copyright © 2011-2022 走看看