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.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
路径总和。题意是给一个二叉树和一个数字sum。求是否有这样一条路径可以使得二叉树从根节点到叶子节点经过的所有的节点值之和等于sum。此题可以用BFS和DFS两种做法解决。
DFS/recursive
时间O(n)
空间O(h)
JavaScript实现
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val, left, right) { 4 * this.val = (val===undefined ? 0 : val) 5 * this.left = (left===undefined ? null : left) 6 * this.right = (right===undefined ? null : right) 7 * } 8 */ 9 /** 10 * @param {TreeNode} root 11 * @param {number} sum 12 * @return {boolean} 13 */ 14 var hasPathSum = function (root, sum) { 15 if (root === null) { 16 return false; 17 } 18 if (root.left === null && root.right === null) { 19 return sum === root.val; 20 } 21 return ( 22 hasPathSum(root.left, sum - root.val) || 23 hasPathSum(root.right, sum - root.val) 24 ); 25 };
Java实现
1 class Solution { 2 public boolean hasPathSum(TreeNode root, int sum) { 3 if (root == null) { 4 return false; 5 } 6 if (root.left == null && root.right == null) { 7 return sum == root.val; 8 } 9 return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 10 } 11 }
BFS/iterative
用一个stack存储遍历到的节点。当加入某个节点的时候,如果这个节点没有孩子节点,需要判断加入这个节点之后的值是否等于sum;如果这个节点有孩子节点,接着遍历它的孩子节点,将cur.val + cur.left.val (cur.val + cur.right.val)加入stack。
时间O(n)
空间O(n) - n is the number of nodes
JavaScript实现
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val, left, right) { 4 * this.val = (val===undefined ? 0 : val) 5 * this.left = (left===undefined ? null : left) 6 * this.right = (right===undefined ? null : right) 7 * } 8 */ 9 /** 10 * @param {TreeNode} root 11 * @param {number} sum 12 * @return {boolean} 13 */ 14 var hasPathSum = function (root, sum) { 15 if (!root) { 16 return false; 17 } 18 let stack = [root]; 19 while (stack.length) { 20 let cur = stack.pop(); 21 if (!cur.left && !cur.right && cur.val === sum) { 22 return true; 23 } 24 if (cur.right) { 25 cur.right.val += cur.val; 26 stack.push(cur.right); 27 } 28 if (cur.left) { 29 cur.left.val += cur.val; 30 stack.push(cur.left); 31 } 32 } 33 return false; 34 };
Java实现
1 class Solution { 2 public boolean hasPathSum(TreeNode root, int sum) { 3 // corner case 4 if (root == null) { 5 return false; 6 } 7 8 // normal case 9 Stack<TreeNode> stack = new Stack<>(); 10 stack.push(root); 11 while (!stack.isEmpty()) { 12 TreeNode cur = stack.pop(); 13 if (cur.left == null && cur.right == null) { 14 if (cur.val == sum) { 15 return true; 16 } 17 } 18 if (cur.right != null) { 19 stack.push(cur.right); 20 cur.right.val += cur.val; 21 } 22 if (cur.left != null) { 23 stack.push(cur.left); 24 cur.left.val += cur.val; 25 } 26 } 27 return false; 28 } 29 }
相关题目