题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */ //方法一:递归 function preOrder(root,sum,res){ if(root == null){ return false; } res += root.val; if(res == sum && root.left == null && root.right == null){ return true; } return preOrder(root.left,sum,res) || preOrder(root.right,sum,res); } //方法二:dfs + 回溯 function dfs(curNode ,sum){ if(curNode == null){ return false; } sum -= curNode.val; if(curNode.left == null && curNode.right == null && sum == 0){ return true; } return dfs(curNode.left,sum) || dfs(curNode.right,sum); } function hasPathSum( root , sum ) { // write code here if(root == null){ return false; } // return dfs(root,sum); //方法一:深度遍历+回溯 return preOrder(root,sum,0) //方法二:递归 //深度遍历二叉树 返回遍历数组(自己练习写dfs遍历二叉树【和这个题无关】) // let stack = []; // let res = [] // stack.push(root); // while(stack.length > 0){ // let node = stack.pop(); // if(node.right != null ){ // stack.push(node.right); // } // if(node.left != null){ // stack.push(node.left); // } // res.push(node.val); // } } module.exports = { hasPathSum : hasPathSum };#我的实习求职记录#