Problem
Find the sum of all left leaves in a given binary tree.
Example:
3 / 9 20 / 15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Solution - Recursiveclass Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null) return 0; int res = 0; if (root.left != null) { if (root.left.left == null && root.left.right == null) res += root.left.val; else res += sumOfLeftLeaves(root.left); } res += sumOfLeftLeaves(root.right); return res; } }Solution - Iterative
class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null) return 0; int res = 0; Dequestack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode cur = stack.pop(); if (cur.left != null) { if (cur.left.left == null && cur.left.right == null) { res += cur.left.val; } else { stack.push(cur.left); } } if (cur.right != null) { if (cur.right.left != null || cur.right.right != null) { stack.push(cur.right); } } } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/72380.html
摘要:解題思路這個(gè)題目其實(shí)就是基于先序遍歷,用遞歸和非遞歸思想都可以。遞歸求所有左葉子節(jié)點(diǎn)的和,我們可以將其分解為左子樹的左葉子和右子樹的左葉子和遞歸結(jié)束條件找到左葉子節(jié)點(diǎn),就可以返回該節(jié)點(diǎn)的。代碼非遞歸判斷是否為左葉子節(jié)點(diǎn)遞歸 Sum of Left LeavesFind the sum of all left leaves in a given binary tree. Example:...
摘要:月下半旬攻略道題,目前已攻略題。目前簡(jiǎn)單難度攻略已經(jīng)到題,所以后面會(huì)調(diào)整自己,在刷算法與數(shù)據(jù)結(jié)構(gòu)的同時(shí),攻略中等難度的題目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道題,目前已攻略 100 題。 一 目錄 不折騰的前端,和咸魚有什么區(qū)別...
摘要:在線網(wǎng)站地址我的微信公眾號(hào)完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號(hào): showImg(htt...
Problem Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate no...
摘要:二叉樹邊界題意高頻題,必須熟練掌握。逆時(shí)針打印二叉樹邊界。解題思路根據(jù)觀察,我們發(fā)現(xiàn)當(dāng)為左邊界時(shí),也是左邊界當(dāng)為左邊界時(shí),為空,則也可以左邊界。先加入左邊,加入,然后得到兩個(gè)子樹加入,最后加入右邊界。 LeetCode 545. Boundary of Binary Tree 二叉樹邊界Given a binary tree, return the values of its boun...
閱讀 736·2021-08-17 10:11
閱讀 1600·2019-08-30 11:15
閱讀 1025·2019-08-26 13:54
閱讀 3511·2019-08-26 11:47
閱讀 1224·2019-08-26 10:20
閱讀 2823·2019-08-23 18:35
閱讀 1219·2019-08-23 17:52
閱讀 1300·2019-08-23 16:19