leetcode在深度优先算法有2道题目,分别是“path sum”和“path sum2”,思路上是一个顺承的关系。本文借助这2道题目,对树的深度优先搜索进行一个简单的训练。
先看第一题:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 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.
这是第一题,只是最粗暴的搜索就可以解决。具体分为以下几种情况:
1,若node节点为空,返回0
2,若到该节点的值等于sum,且该节点是叶子节点,就返回1
3,若该节点不是叶子结点那就分别遍历左右孩子节点
具体代码如下:
/**
* 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 hasPathSum(TreeNode* root, int sum) {
if (root == NULL){
return 0;
}
else if(sum == root -> val && root -> left == NULL && root -> right == NULL){
return 1;
}
else{
bool a = 0, b = 0;
if (root -> left != NULL){
a = hasPathSum(root -> left, sum - root -> val);
}
if (root -> right != NULL){
b = hasPathSum(root -> right, sum - root -> val);
}
return a || b;
}
}
};
第一道题热身之后,我们来看第二题:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
比起来上一道题,这道题就是要找出来所有符合条件的路径。也就是说,在上一题的基础上,增加一个vector<int>来存储一条路径上的节点,一个vector<vector<int>>来存储路径。具体来说是在每一次检测到中间节点的时候都把它压入vector中,最后判定路径成立的时候压入总的vector中。代码如下:
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > paths;
vector<int> path;
findPaths(root, sum, path, paths);
return paths;
}
private:
void findPaths(TreeNode* node, int sum, vector<int>& path, vector<vector<int> >& paths) {
if (!node) return;
path.push_back(node -> val);
if (!(node -> left) && !(node -> right) && sum == node -> val)
paths.push_back(path);
findPaths(node -> left, sum - node -> val, path, paths);
findPaths(node -> right, sum - node -> val, path, paths);
path.pop_back();
}
};
private中的是寻找每一条路径的算法,找到的符合要求的路径都会压入paths中,在public里面的函数最终return结果。
总的来说,这2道题都是对深度优先搜索的简单应用,我们可以看出,采用结构体写的树的深度优先遍历还是比较简单的,顺序是遍历该节点然后分别遍历左右节点。重点是我们对遍历每一步结果的处理。或许是通过vector,或许是通过其他方式。
个人简介,如有不足请读者不吝赐教。