21.Merge Two Sorted Lists
Description:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists
My C++ code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/ class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(nullptr == l1)
{
return l2;
}
if(nullptr == l2)
{
return l1;
}
if(l1->val < l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
100.Same Tree
Description:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
分析:
题意就是给出两个二叉树,判断是否为相等的二叉树。本题可用递归的思想解决,每个二叉树要么只有一个根,要么就有一个根和一个左子树和一个右子树。左右子树还是二叉树。递归到最后就是判断根结点是否相等了。
My C++ code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(nullptr == p && nullptr == q)
{
return true;
}
else if(nullptr == p || nullptr == q)
{
return false;
}
else
{
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}
};