题目: 合并两个排序的链表
描述:
输入两个单调递增的链表,输出两个链表合成后的链表,
当然我们需要合成后的链表满足单调不减规则。
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);
}