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;
Deque stack = 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;
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72380.html
摘要:解题思路这个题目其实就是基于先序遍历,用递归和非递归思想都可以。递归求所有左叶子节点的和,我们可以将其分解为左子树的左叶子和右子树的左叶子和递归结束条件找到左叶子节点,就可以返回该节点的。代码非递归判断是否为左叶子节点递归 Sum of Left LeavesFind the sum of all left leaves in a given binary tree. Example:...
摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...
摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: 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...
摘要:二叉树边界题意高频题,必须熟练掌握。逆时针打印二叉树边界。解题思路根据观察,我们发现当为左边界时,也是左边界当为左边界时,为空,则也可以左边界。先加入左边,加入,然后得到两个子树加入,最后加入右边界。 LeetCode 545. Boundary of Binary Tree 二叉树边界Given a binary tree, return the values of its boun...
阅读 906·2021-08-17 10:11
阅读 1798·2019-08-30 11:15
阅读 1194·2019-08-26 13:54
阅读 3675·2019-08-26 11:47
阅读 1420·2019-08-26 10:20
阅读 3045·2019-08-23 18:35
阅读 1388·2019-08-23 17:52
阅读 1440·2019-08-23 16:19