【LeetCode每日一题】404. 左叶子之和

【LeetCode每日一题】404. 左叶子之和

404. 左叶子之和

题目来源link
算法思想:树,遍历;

利用树的(左中右,中序遍历,统计左叶子之和)

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