[LeetCode-404]Sum of Left Leaves(java)

2022 ワード

Find the sum of all left leaves in a given binary tree. Example: 3 /\ 9 20 /\ 15 7 There are one left leaves in the binary tree, with values 15 respectively. Return 15. 題意:二叉木のすべての左葉ノードのvalの和を求める.
分析:
  • 左葉接点は、まず葉ノードであることを強調するとともに、左ノードであることを強調し、演算
  • を加える.
  • 再帰的方法
  • を採用する.
  • ツリーが空の場合、0
  • に戻ります.
  • 二叉木の左サブツリーが左サブツリー(左サブツリーには左右の子供ノードがない)である場合、左サブツリーノードのval値+sumOfLeftLeaves(右サブツリー)の値
  • を返す.
  • 二叉木の左、右のサブツリーに子供のノードがある場合は、sumOfLeftLeaves(左サブツリー)+sumOfLeftLeaves(右サブツリー)の値
  • を返します.
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            int sum=0;
            //  root  ,  0
            if(root==null)
            return 0;
            //            ,         val +sumOfLeftLeaves(   )  
            if(root.left!=null && root.left.left==null && root.left.right==null)
            return root.left.val+sumOfLeftLeaves(root.right);
            else
            //        sumOfLeftLeaves(   )+sumOfLeftLeaves(   )  
            return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
     }
    }