Leetcode_#404_左叶子之和

原题:#404_左叶子之和

  • 递归
    • 返回值:返回左子树的左叶子+右子树的左叶子之和
    • 递归操作:遍历左子树和右子树,找到叶子节点并相加
    • 结束条件:根节点为空时结束递归
public int sumOfLeftLeaves(TreeNode root) {
    if (root == null) return 0;
    if (isLeaf(root.left)) return root.left.val + sumOfLeftLeaves(root.right);
    return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}

private boolean isLeaf(TreeNode node){
    if (node == null) return false;
    return node.left == null && node.right == null;
}
原创文章 50 获赞 1 访问量 2927

猜你喜欢

转载自blog.csdn.net/u014642412/article/details/105927323