Path Sum and Delete Node in a Linked List
来源:互联网 发布:手机里js文件怎么打开 编辑:程序博客网 时间:2024/06/06 03:25
今天照例更新数据结构基础,希望各位各取所需,我本人是习惯通过题目通过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);}
0 0
- Path Sum and Delete Node in a Linked List
- "same tree" and "Delete Node in a Linked List"
- leetcode: Delete Node in a Linked List
- LeetCode Delete Node in a Linked List
- Delete Node in a Linked List
- 【leetcode】Delete Node in a Linked List
- Delete Node in a Linked List
- Delete Node in a Linked List
- Leetcode: Delete Node in a Linked List
- 237 - Delete Node in a Linked List
- Delete Node in a Linked List
- [LeetCode]Delete Node in a Linked List
- Delete Node in a Linked List
- 【leetcode】Delete Node in a Linked List
- Delete Node in a Linked List
- 237 Delete Node in a Linked List
- Leetcode Delete Node in a Linked List
- LeetCode || Delete Node in a Linked List
- Android控件TextView显示html文件中的图片
- [置顶]Android Studio 初体验
- 参看caffe中三通道彩色图像的卷积过程
- 友元(friend)
- JZOJ 4.8 2435——校门外的树【树状数组】
- Path Sum and Delete Node in a Linked List
- Cell系列的update机制与个性化使用
- 浅谈数组(二)
- bzoj1211: [HNOI2004]树的计数
- 图解TCP/IP笔记(三)
- 线性表的有关操作
- week7- Dynamic Programming-NO.516. Longest Palindromic Subsequence
- android开发之 java.lang.NoClassDefFoundError:retrofit2.Retrofit$Builder 错误解决
- Java8 Mac安装