您的位置:首页 > 其它

树类型的题目的总结 leetcode 112, 235

2017-08-12 09:57 302 查看
首先我们知道,树是一种递归的结构,所以在解决树的问题上,我们经常可以使用递归的求解方式求解,思路非常清晰,代码也非常简洁。掌握了基本的思路之后,再碰到类似的题目之后,我们可以使用相类似的思路去想解决的办法,然后代码实现思路。

leetcode 112

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
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);
}
}


这事一道easy题,想到了递归的思路之后就顺理成章。首先先写当前的返回条件,然后在写返回true时候的情况。

Leetcode 235

这道题目仍然可以使用递归的方式去求解,在递归求解的过程中,我们要注意题目中binary search tree,可以利用binary search tree的特点作为返回的判断依据。

如果p和q分别在两个不同的子树上,那么直接返回root, 如果p和q在同一棵子树上,那么就递归求解。直到返回答案。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode result = root;
if((p.val > root.val && q.val < root.val) || (p.val < root.val && q.val > root.val)) return root;
if(p.val > root.val && q.val > root.val)
result = lowestCommonAncestor(root.right, p,q);
if(p.val < root.val && q.val < root.val)
result = lowestCommonAncestor(root.left, p,q);
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: