12、合并两个排序的链表、树的子结构

题目: 合并两个排序的链表

描述:

输入两个单调递增的链表,输出两个链表合成后的链表,

当然我们需要合成后的链表满足单调不减规则。

php 复制代码
<?php
/*class ListNode{
    var $val;
    var $next = NULL;
    function __construct($x){
        $this->val = $x;
    }
}*/
function Merge($pHead1, $pHead2)
{
    if($pHead1 == NULL)
        return $pHead2;
    elseif($pHead2 == NULL)
        return $pHead1;
    $pMergeHead = new ListNode(null);
    if($pHead1->val < $pHead2->val){
        $pMergeHead = $pHead1;
        $pMergeHead->next = Merge($pHead1->next, $pHead2);
    }else{
        $pMergeHead = $pHead2;
        $pMergeHead->next = Merge($pHead1, $pHead2->next);
    }
    return $pMergeHead;
}

题目: 树的子结构

描述:

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

php 复制代码
<?php

/*class TreeNode{
    var $val;
    var $left = NULL;
    var $right = NULL;
    function __construct($val){
        $this->val = $val;
    }
}*/
function HasSubtree($pRoot1, $pRoot2)
{
        // write code here
   $re = false;
    if($pRoot1!=null && $pRoot2 != null)
        {
        if($pRoot1->val==$pRoot2->val)
            $re = isSubtree($pRoot1,$pRoot2);
        if(!$re)
            $re = HasSubtree($pRoot1->left, $pRoot2);
        if(!$re)
            $re = HasSubtree($pRoot1->right, $pRoot2);
    }
    return $re;
}
function isSubtree($pRoot1,$pRoot2){
    if($pRoot2 == null) return true;
    if($pRoot1 == null) return false;
    if($pRoot1->val != $pRoot2->val) return false;
    return isSubtree($pRoot1->left,$pRoot2->left)&&isSubtree($pRoot1->right,$pRoot2->right);
}
相关推荐
饮水桶_T17 小时前
JAVA IO流笔记
开发语言·数据结构·算法
wo_jack1 天前
C++ 入门笔记(十七):list 入门 —— 为什么 list 不能 sort?
数据结构·c++·面试·stl·list
zaizai10071 天前
算法(左程云)1
数据结构
charliejohn1 天前
计算机考研 408 数据结构 图论-关键路径
数据结构·图论
David猪大卫2 天前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
vvilkim2 天前
数据结构类型、区别与应用场景:一篇讲透选型逻辑
数据结构
阿卡好可爱2 天前
Lua 热更新不生效:改完文件线上仍是旧逻辑,package.loaded 与 upvalue 重绑定详解
数据结构·分布式·后端·架构·lua
心仪久了会沦陷3 天前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
码少女3 天前
数据结构——图的基础
数据结构