日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 404. 左叶子之和(Sum of Left Leaves)

發布時間:2024/8/26 编程问答 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 404. 左叶子之和(Sum of Left Leaves) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

404. 左葉子之和
404. Sum of Left Leaves

LeetCode404. Sum of Left Leaves

題目描述
計算給定二叉樹的所有左葉子之和。

示例:

3/ \9 20/ \15 7

在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24。

Java 實現
TreeNode 結構

class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;} }

Recursive

class Solution {private int sum = 0;public int sumOfLeftLeaves(TreeNode root) {if (root == null) {return 0;}if (root.left != null && root.left.left == null && root.left.right == null) {sum += root.left.val;}sumOfLeftLeaves(root.left);sumOfLeftLeaves(root.right);return sum;} } class Solution {public int sumOfLeftLeaves(TreeNode root) {int count = 0;if (root == null) {return 0;}if (root.left != null) {if (root.left.left == null && root.left.right == null) {count += root.left.val;} else {count += sumOfLeftLeaves(root.left);}}count += sumOfLeftLeaves(root.right);return count;} }

Iterative

import java.util.Stack; class Solution {public int sumOfLeftLeaves(TreeNode root) {int count = 0;Stack<TreeNode> stack = new Stack<>();if (root == null) {return 0;}stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();if (node.left != null) {if (node.left.left == null && node.left.right == null) {count += node.left.val;} else {stack.push(node.left);}}if (node.right != null) {if (node.right.left != null || node.right.right != null) {stack.push(node.right);}}}return count;} }

主測試類

public class Test {public static void main(String[] args) {Solution tree = new Solution();/* create a tree */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);System.out.println(tree.sumOfLeftLeaves(root));} }

運行結果

24

相似題目

  • 求二叉樹中葉子節點的個數

參考資料

  • https://leetcode.com/problems/sum-of-left-leaves/
  • https://leetcode-cn.com/problems/sum-of-left-leaves/

轉載于:https://www.cnblogs.com/hglibin/p/10849527.html

總結

以上是生活随笔為你收集整理的LeetCode 404. 左叶子之和(Sum of Left Leaves)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。