当前位置:网站首页>【LeetCode】404. Sum of left leaves (2 brushes of wrong questions)

【LeetCode】404. Sum of left leaves (2 brushes of wrong questions)

2022-07-05 02:20:00 Kaimar

0
1

  • Ideas
    Divided into two steps , First, find the left leaf node , Second, sum . Here we are going to use the recursive method of post order traversal . How to judge whether it is left or right , What is needed is the root node to judge !
    Recursive parameters and return values : The parameter is the current node , Return value , If the left leaf node returns the current node value , Otherwise return to 0;
    The termination condition of recursion : When the node is empty, return ;
    Recursive single-layer logic : Use post order traversal , Then the corresponding is left and right middle , The part on the left corresponds to whether it is a leaf node ;
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func sumOfLeftLeaves(root *TreeNode) int {
    
    if root == nil {
    
        return 0
    }
    //  Left 
    leftSum := sumOfLeftLeaves(root.Left)
    //  Right 
    rightSum := sumOfLeftLeaves(root.Right)
    //  in 
    //  When you encounter the left leaf node , Record the values , Then the sum of the left leaves of the left subtree is obtained recursively , And the sum of the left leaves of the right subtree , The sum is the sum of the left leaves of the whole tree .
    mid := 0
    if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
    
        mid = root.Left.Val
    }
    return leftSum + mid + rightSum
}

2

原网站

版权声明
本文为[Kaimar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140933283156.html