2021.11.10 - SX07-16.左叶子之和

1. 题目

在这里插入图片描述

2. 思路

(1) DFS

  • 利用深度优先搜索遍历二叉树,若结点为左叶子结点,则记录该结点的值即可。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class TreeNode {
    
    
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    
    
    }

    TreeNode(int val) {
    
    
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
    
    
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    
    
    private int sum;

    public int sumOfLeftLeaves(TreeNode root) {
    
    
        sum = 0;
        preorder(root);
        return sum;
    }

    private void preorder(TreeNode root) {
    
    
        if (root == null) {
    
    
            return;
        }
        if (root.left != null && root.left.left == null && root.left.right == null) {
    
    
            sum += root.left.val;
        }
        preorder(root.left);
        preorder(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121243600