【leetcode】112. Path Sum

来源:互联网 发布:php array sort 排序 编辑:程序博客网 时间:2024/05/29 12:44

题目描述:

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,
这里写图片描述
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

思路:

用深度优先搜索遍历整个二叉树。这里我用迭代实现DFS,一般用堆栈实现。此外,为了找到节点和为sum的路径,想到用另一个堆栈来记录遍历到的节点到根节点的和。

代码如下:

public class Solution {    public boolean hasPathSum(TreeNode root, int sum) {        if(root == null) return false;        Stack<TreeNode> node = new Stack();//记录遍历到的节点        Stack<Integer> valSum = new Stack();//记录节点到根节点的和        node.push(root);        valSum.push(root.val);        while( !node.isEmpty() ){            TreeNode tempRoot = node.pop();            int getSum = valSum.pop();            if(getSum == sum && tempRoot.left == null && tempRoot.right == null){             return true;             }            if(tempRoot.left != null){                node.push(tempRoot.left);                valSum.push(tempRoot.left.val+getSum);            }            if(tempRoot.right != null){                node.push(tempRoot.right);                valSum.push(tempRoot.right.val+getSum);            }        }        return false;    }}

测试通过。

写完了DFS,再试着用BFS实现层次遍历二叉树。思路差不多:

public class Solution {   public boolean hasPathSum(TreeNode root, int sum) {        if (root == null) return false;        Queue<TreeNode> queue = new LinkedList<TreeNode>();        Queue<Integer> value = new LinkedList<Integer>();        queue.offer(root);         value.offer(root.val);         while(!queue.isEmpty()){                   TreeNode tempRoot = queue.poll();             int getSum= value.poll();            if (tempRoot.left == null && tempRoot.right == null && getSum == sum){                return true;            }             if (tempRoot.left != null) {                queue.offer(tempRoot.left);                value.offer(getSum + tempRoot.left.val);              }            if (tempRoot.right != null) {                queue.offer(tempRoot.right);                value.offer(getSum + tempRoot.right.val);                             }        }        return false;   }}

看了一下top答案,都是用递归实现DFS的,代码更简洁。如下:

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) return true;        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }
1 0
原创粉丝点击