leetcode 404. Sum of Left Leaves
来源:互联网 发布:teambition类似软件 编辑:程序博客网 时间:2024/06/06 10:53
Find the sum of all left leaves in a given binary tree.
如果采用递归的解法,就需要判断前后两次迭代的关系。
如果树只有一个节点,需要判断其与父节点的关系,如果该节点是左孩子,就直接返回其值,如果是右孩子就返回0。如果还有孩子,就往下递归。
注意到这里有个与父节点关系,按照一般的递归是无法保持这个信息,同时为了递归的简便,不太方便在每次递归里还判断下两层的情况,最好只看是判断有无孩子。这样我们可以设置一个标志位,来记住进入该节点时,该节点与父节点的关系。默认根节点是父节点的右孩子。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root==null) return 0; int res = 0; res = left_sum(root,1); return res; } //dir, 0:left, 1:right int left_sum(TreeNode root, int dir){ int res = 0; if(root.left==null && root.right==null){ if(dir==0) return root.val; else return 0; } if(root.left!=null) res += left_sum(root.left, 0); if(root.right!=null) res += left_sum(root.right,1); return res; }}
阅读全文
0 0
- LeetCode笔记:404. Sum of Left Leaves
- 【leetcode】404. Sum of Left Leaves【E】
- LeetCode—404. Sum of Left Leaves
- [LeetCode]404. Sum of Left Leaves
- Leetcode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- 404. Sum of Left Leaves - leetcode
- [LeetCode]--404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- [leetcode]404. Sum of Left Leaves
- LeetCode-404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- leetcode 404. Sum of Left Leaves
- leetcode(88).404. Sum of Left Leaves
- 【LeetCode】 404. Sum of Left Leaves
- leetcode 404. Sum of Left Leaves
- [Leetcode]404. Sum of Left Leaves
- 伴随矩阵介绍及C++实现
- python:生成器
- MySQL高可用最佳应用与实践
- Windows 系统操作系列API-(1)-SHGetFolderPath
- 使用命名管道的OVERLAPPED方式实现非阻塞模式编程
- leetcode 404. Sum of Left Leaves
- 安卓学习笔记(七):服务 跟着API指南来学习
- Dlib库【8】——多层神经网络
- 线段相交
- socket 连接超时处理 java
- hash专题
- android studio配置kotlin
- 【Rest】REST和SOAP Web Service的区别比较
- ASP.NET Core(二)【入门】