二叉树

34 阅读1分钟

一、题目描述:

给定一个二叉树和一个目标和,判断该树中是否存在从根节点到叶子节点的路径,使得路径上所有节点值相加等于目标和。

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

二叉树最近公共祖先:


public class LowestCommonAncestor {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        return left != null ? left : right;
    }
}