leetcode Path Sum
题目:给定一颗数,以及一个数sum。判断是否存在从树到叶节点的和等于sum。
例如:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
rerun true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
利用递归,和Minimum Depth类似,要考虑到叶节点才返回。很容易得到递归式子:
/** * Definition for binary tree * 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) return false; if (!root -> left && !root -> right) return sum == root -> val; bool lf = false, ri = false; if (root -> left) lf = hasPathSum(root -> left, sum - root -> val); if (root -> right) ri = hasPathSum(root -> right, sum - root -> val); return lf || ri; } };
需要注意的是当叶子节点当根节点左右子树都为空是才为叶子节点,如果有一个飞空,那么根节点自身就不是叶子节点,所以不存在只有根节点的解。
同时记录一下非递归的解:
public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; LinkedList<TreeNode> nodes = new LinkedList<TreeNode>(); LinkedList<Integer> values = new LinkedList<Integer>(); nodes.add(root); values.add(root.val); while(!nodes.isEmpty()){ TreeNode curr = nodes.poll(); int sumValue = values.poll(); if(curr.left == null && curr.right == null && sumValue==sum){ return true; } if(curr.left != null){ nodes.add(curr.left); values.add(sumValue+curr.left.val); } if(curr.right != null){ nodes.add(curr.right); values.add(sumValue+curr.right.val); } } return false; }