题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f
借鉴了JZ34 二叉树中和为某一值的路径(二)的答题思路
- 写一个深度遍历的递归函数dfs,遍历过程中每经过一个结点,就将sum减去这个结点的值,每个子树都重复这样的路径搜索过程,递归停止条件为结点为空,也就是搜索全部结点;
- 用一个全局变量flag计量sum为0的次数,即为路径数量(路径不用以叶子结点为终点,就可以被计数);
- 在主函数中调用这个dfs函数,意味着从根结点开始搜索,再递归调用主函数本身,使根结点的子结点可以作为路径起点,再去搜寻。
int flag=0; public int FindPath (TreeNode root, int sum) { // write code here if(root==null)return 0; dfs(root,sum); FindPath(root.left,sum); FindPath(root.right,sum); return flag; } public void dfs(TreeNode root,int sum){ if(root==null)return; sum -= root.val; if(sum==0){ flag++; } dfs(root.left,sum); dfs(root.right,sum); } }