LeetCode--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.

For 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.

问题描述:给出一个二叉树和一个整数,问是否存在一条路径,使相加的和与sum相等,若存在,返回true;若不存在,返回false。

问题解决:找一条路径,也就是对二叉树进行先序遍历(这里也就是深度优先遍历)。有递归和非递归两种方式。

解法一:递归法。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)
            return false;
        if((root.left==null && root.right==null) && root.val==sum)
            return true;
        return hasPathSum(root.left, sum-root.val) || 
                hasPathSum(root.right, sum-root.val);    //这里用sum减去每个节点上的val,如果最后叶节点的val与剩下的sum相等,则说明这一条便是路径
    }
}

解法二:非递归法。

    public boolean hasPathSum(TreeNode root, int sum) {
        LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
        LinkedList<Integer> vals = new LinkedList<Integer>();
        if(root==null)
            return false;
        
        //把根节点放入list
        nodes.add(root);
        vals.add(root.val);
        while(!nodes.isEmpty()){
            TreeNode curr = nodes.poll();
            int cn = vals.poll();
            
            if((curr.left==null && curr.right==null) && cn==sum)
                return true;
            if(curr.left!=null){
                nodes.add(curr.left);
                vals.add(cn+curr.left.val);
            }
            if(curr.right!=null){
                nodes.add(curr.right);
                vals.add(curr.right.val+cn);
            }
        }
        return false;
    }

 

posted @ 2015-05-26 10:38  江湖小妞  阅读(160)  评论(0编辑  收藏  举报