算法结构与设计基础作业第九周

本文介绍两种常见的数据结构操作:合并两个有序链表及比较两棵二叉树是否相同。对于有序链表合并,通过递归方式合并两个链表节点;对于二叉树比较,则采用递归思想,检查每对对应节点是否相等。

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);  
        }
    }
};



     


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值