[LeetCode Daily Question] 404.左の葉の合計

[LeetCode Daily Question] 404.左の葉の合計

404.左の葉の合計

トピックソースリンク
アルゴリズムのアイデア:ツリー、トラバーサル。

ツリーの使用(左中右、中次トラバーサル、左葉の合計を数える)

Javaコード

/**
 * 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[] res = {
    
    0};//要使用引用类型,指针传递值;使用int,无效
        sumOfLeftLeavesdigui(root, false, res);//递归中序遍历
        return res[0];
    }

    public void sumOfLeftLeavesdigui(TreeNode root, boolean left, int[] res){
    
    
        if(root == null){
    
    
            return;
        }//递归返回条件
        sumOfLeftLeavesdigui(root.left, true, res);//向左遍历,标记为左子树true
        if(left && root.left == null && root.right == null){
    
    
            res[0] += root.val;
        }//如果是左子树,判断是否是叶子,如果是,将数值相加到res
        sumOfLeftLeavesdigui(root.right, false, res);//向右遍历,标记为右子树false
    }
}

おすすめ

転載: blog.csdn.net/qq_39457586/article/details/108686080