力扣每日一题,404. 左叶子之和

我以为1ms够快了,万万没想到个个都是0ms,太强了。
在这里插入图片描述
在这里插入图片描述

题目描述

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

 

思路

还是复习遍历的简单题,把遍历模板烂熟于心吧。

二叉树前序遍历模板(迭代实现)

import java.util.Stack;

public class Solution {
    public static void main(String[] args) {
    	/*
         *       5
         *      / \
         *     4   3
         *    / \
         *   1   2
         */
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(2);
        new Solution().preOrder(root);
    }
    // 迭代实现
    void preOrder(TreeNode root) {
    	if (root != null) {
    		Stack<TreeNode> stack = new Stack<TreeNode>();
    		stack.push(root);
    		while (!stack.isEmpty()) {
    			TreeNode node = stack.pop();
    			System.out.print(node.val + " ");
    			if (node.right != null)
    				stack.push(node.right);
    			if (node.left != null)
    				stack.push(node.left);
    		}
    	}
    }
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }
}

提交代码

套用模板,需增加的地方是,每次处理左子树的时候判断下是不是叶子,是就将值加给sum

package 左叶子之和;

import java.util.Deque;
import java.util.LinkedList;

import org.junit.Test;

public class Solution {
	@Test
	public void test1() throws Exception {
		TreeNode root = new TreeNode(3);
		root.left = new TreeNode(9);
		root.right = new TreeNode(20);
		root.right.left = new TreeNode(15);
		root.right.right = new TreeNode(7);
		sumOfLeftLeaves(root);

	}

	public int sumOfLeftLeaves(TreeNode root) {
		if (root != null){
			Deque<TreeNode> queue = new LinkedList<TreeNode>();
			queue.push(root);
			int sum = 0;
			while (!queue.isEmpty()) {
				root = queue.pop();
				if (root.right != null) {
					queue.push(root.right);
				}
				if (root.left != null) {
					if (root.left.left == null && root.left.right == null) {
						sum += root.left.val;
					}
					queue.push(root.left);
				}
			}
			return sum;
		}
		return 0;
	}
}
class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int x) {
		val = x;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值