美文网首页
404-左叶子之和

404-左叶子之和

作者: 饮酒醉回忆 | 来源:发表于2019-07-22 09:36 被阅读0次

    左叶子之和

    题目

    计算给定二叉树的所有左叶子之和。

    示例:

        3
       / \
      9  20
        /  \
       15   7
    

    在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/sum-of-left-leaves
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路

    一般来说二叉树的题目中有两种思路,一种递归,一种循环.本题使用递归相对简单,因此选择递归

    代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            //这道题只有左叶子节点的和要相加,因此可以分成首先判断是否是叶子节点,然后将叶子节点相加
            int sum = 0;
            return recursion(sum,root,false);
        }
        
        public int recursion(int num,TreeNode root,boolean isLeft){
            if(root == null){
                return 0;
            }
            if(root.right == null && root.left == null && isLeft){
                num+=root.val;
                return num;
            }
            return recursion(num,root.right,false) + recursion(num,root.left,true);
        }
    }
    

    相关文章

      网友评论

          本文标题:404-左叶子之和

          本文链接:https://www.haomeiwen.com/subject/wnqilctx.html