Path Sum and Delete Node in a Linked List

今天照例更新数据结构基础,希望各位各取所需,我本人是习惯通过题目通过code来加深对数据结构以及某些算法的理解。

现在首先我们还是来看看二叉树相关的题目:
Path sum,leetcode上给出的演示如下:

For example:
Given the below binary tree and sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

题目判定,能否在某二叉树root中找到 各节点和为sum的路径。

首先老规矩分两种方法,DFS和BFS(注意因为要用到队列,故而BFS 是通过C++来实现的)。
首先我们看,通过BFS我们一层一层就遍历
算法分析:准备两个队列,一个为node,保存节点,一个为value,保存当前节点与之前节点的之和的值,下面看代码:

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
          if(root == NULL)  return false;
          queue<TreeNode*>     node;
          queue<int>         value;
          node.push(root);
          value.push(root->val);
       // 开启遍历
       while(node.size() > 0) {
         TreeNode*   cur = node.front();
         node.pop();
         int sumvalue = value.front;
         if(cur->left == NULL && cur->right == NULL &&         sumvalue == sum){
              return true;         
      }
            if(cur->left !=NULL){
                 node.push(cur->left);
                 value.push(sumvalue + cur->left->val);
            }

            if(cur->right !=NULL) {
                 node.push(cur->right);
                 vaule.push(sumvalue + cur->right->val);
            }

       }
         return false;
}

好了BSF方法已经完成,比较直接不需要太多思维,接下来看看DFS
DFS显得简洁很多,直接利用递归。

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
             if(root == NULL)  return false;
             if(root->left == NULL && root->right == NULL
                    && root->val == sum)
                    return true;
              // 开启递归
          return  hasPathSum(root->left, sum- root->val) 
              ||hasPathSum(root->right, sum - root->val);
     }

再看链表相关的:

Delete Node in a Linked List
感觉这个题目没什么好讲的直接看代码:

void deleteNode(struct ListNode* node) {
    node->val = node->next->val;

    struct ListNode*  tmp = node->next;
    node->next = tmp->next;

    free(tmp);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值