网站注册会绑定式收费吗,国家建筑网官网,上海环球金融中心介绍,app公司是怎么赚钱的404.左叶子之和
算法链接:
404. 左叶子之和 - 力扣#xff08;LeetCode#xff09; 类型: 二叉树 难度: 简单
思路#xff1a;要判断一个节点是否为左叶子节点#xff0c;只能通过其父节点进行判断。
题解:
/*** Definition for a binary tree node.* public class Tr…404.左叶子之和
算法链接:
404. 左叶子之和 - 力扣LeetCode 类型: 二叉树 难度: 简单
思路要判断一个节点是否为左叶子节点只能通过其父节点进行判断。
题解:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val val;* this.left left;* this.right right;* }* }*/
//解法1递归法
class Solution {public int sumOfLeftLeaves(TreeNode root) {if(root null||root.leftnullroot.rightnull){return 0;}int l sumOfLeftLeaves(root.left);if(root.left!nullroot.left.leftnullroot.left.rightnull){l root.left.val;}int r sumOfLeftLeaves(root.right);return lr;}
}
//解法2迭代法
513.找树左下角的值
算法链接:
513. 找树左下角的值 - 力扣LeetCode 类型: 二叉树 难度: 中等
思路层序遍历法当每一层插入第一个同一层最左边的节点时记录该节点并且将其返回。 递归法前序遍历判断当层数1时记录当前值。顺序中、左、右
题解:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val val;* this.left left;* this.right right;* }* }*/
//解法1层序遍历迭代法
class Solution {public int findBottomLeftValue(TreeNode root) {int res 0;DequeTreeNode que new LinkedList();que.offer(root);while(!que.isEmpty()){int size que.size();for(int i 0;isize;i){TreeNode poll que.poll();if(i0){res poll.val;}if(poll.left!null){que.offer(poll.left);}if(poll.right!null){que.offer(poll.right);}}}return res;}
}
//解法2递归法
112. 路径总和
算法链接:
112. 路径总和 - 力扣LeetCode 类型: 二叉树 难度: 简单
题解:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val val;* this.left left;* this.right right;* }* }*/
class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {return search(root,0,targetSum);}boolean search(TreeNode root,int sum,int targetSum){if(root null){return false;}sumroot.val;if(root.leftnullroot.rightnull){return sumtargetSum;}boolean l search(root.left,sum,targetSum);boolean r search(root.right,sum,targetSum);return l||r;}
}