Path Sum 一个树里边,看看有没有一条路径上边的和等于给定的数

来源:互联网 发布:淘宝主播逢丁吉吉 编辑:程序博客网 时间:2024/05/01 05:30

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.


出处:http://blog.csdn.net/aresgod/article/details/39400643


用到了递归(递归我还是不会用啊,伤心)

下边人家这个写法很巧妙的一点就是,没有去累加,而是每走一步,就去判断给定的sum与这个节点的数值相不相等,等于返回,不等于时,把两者的差作为下一步递归的sum


/**
 * 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) {
        return pathExist(root,sum);
    }
    private boolean pathExist(TreeNode Node,int sum){
        if(Node==null)  return false;
        if(Node.left==null && Node.right==null) return(sum==Node.val);
        else return(pathExist(Node.left,sum-Node.val) || pathExist(Node.right,sum-Node.val));
    }
}

下边的出处:http://www.cnblogs.com/springfor/p/3879825.html?utm_source=tuicool&utm_medium=referral

你看看,比上边的简洁了不少吧,明明自己都可以递归,上边非要自定义一个函数

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


下边的这个是中规中矩的写法,没有用到递归,但是很值得一看。

For the tree above, the queue would be: 5 - 4 - 8 - 11 - 13 - 4 - 7 - 2 - 1. It will check node 13, 7, 2 and 1. This is a typical breadth first search(BFS) problem.

想一想为什么会用LinkedList,看一看TreeNodeLinkedList里边的poll会返回List的头节点,并且会删除该节点,因为是头节点,所以实现了breadth first search(BFS)即横向优先搜索(广度优先搜索),按着程序走一遍流程,便很清楚了

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)  return false;
        LinkedList<TreeNode> node=new LinkedList<TreeNode>();
        LinkedList<Integer> sumval=new LinkedList<Integer>();
        node.add(root);
        sumval.add(root.val);
 
        while(!node.isEmpty()){     //判断的是链表是否为空
            TreeNode getnode=node.poll();   //用poll得到链表的头节点,实现广度优先搜索
            int getval=sumval.poll();
             
            if(getnode.left==null && getnode.right==null && getval==sum)   return true;
            if(getnode.left!=null){
                node.add(getnode.left);
                sumval.add(getval+getnode.left.val);
            }
            if(getnode.right!=null){
                node.add(getnode.right);
                sumval.add(getval+getnode.right.val);
            }
        }
        return false;
    }
}

0 0
原创粉丝点击