112. Path Sum

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      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

大神用了递归的方法,比较快,我自己用的非递归,很慢~

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
    
        if(root.left == null && root.right == null && sum - root.val == 0) return true;
    
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

我自己



import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null)
return false;


List<TreeNode> treeArray = new ArrayList<TreeNode>();
treeArray.add(root);
Set<Integer> sumSet = new HashSet<Integer>();


while (!treeArray.isEmpty()) {
int length = treeArray.size();
for (int i = 0; i < length; i++) {
TreeNode node = treeArray.get(0);
treeArray.remove(0);
                
if (node.left == null && node.right == null) {
sumSet.add(node.val);
}


if (node.left != null) {
int leftVal=node.left.val;
node.left.val=leftVal+node.val;
treeArray.add(node.left);
}


if (node.right != null) {
int rightVal=node.right.val;
node.right.val=rightVal+node.val;
treeArray.add(node.right);
}
}
}
return sumSet.contains(sum);
    }
}


扫描二维码关注公众号,回复: 762382 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_39525565/article/details/80257860