您的位置:首页 > 其它

112. Path Sum

2016-06-23 10:51 155 查看
题目:

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.

Hide Tags
Tree Depth-first Search

链接:http://leetcode.com/problems/path-sum/

一刷,DFS

class Solution(object):
def hasPathSum(self, root, sum):
if not root:
return False
if not root.left and not root.right and sum == root.val:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)


2/17/2017, Java, performance only bit 2%...

用类似前序遍历的方法。一定要注意什么时候需要pop,每次入栈的都是什么值。

注意叶节点是在stack的peek上,空节点不在。

recursive方法远好于iterative算法

public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
TreeNode node = root;
TreeNode previous = null;
Stack<TreeNode> stack = new Stack<>();
int value = sum;
stack.push(root);
value -= root.val;

while (!stack.isEmpty()) {
node = stack.peek();
if (previous == null || previous.left == node || previous.right == node) {
if (node.left == null && node.right == null) {
if (value == 0) return true;
else {
previous = stack.pop();
value += previous.val;
}
} else if (node.left != null) {
stack.push(node.left);
value -= node.left.val;
previous = node;
} else if (node.right != null) {
stack.push(node.right);
value -= node.right.val;
previous = node;
}
} else if (previous == node.left) {
if (node.right != null) {
stack.push(node.right);
value -= node.right.val;
previous = node;
} else {
previous = stack.pop();
value += previous.val;
}

} else if (previous == node.right) {
previous = stack.pop();
value += previous.val;
}
}
return false;
}
}


5/8/2017

算法班

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: