Leetcode 刷题Day18--------------------二叉树
1. 找树左下角的值(递归难,迭代的层序遍历更容易)(513)
- 题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
- 文章讲解/视频讲解:https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<TreeNode>();
int res=0;
queue.add(root);
while(!queue.isEmpty()){
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode node=queue.poll();
if(i==0) res=node.val;
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
}
}
return res;
}
}
2. 路径总和(112) 113.路径总和ii
- 题目链接:
- 文章讲解/视频讲解:https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
targetSum-=root.val;
if(root.left==null && root.right==null){
return targetSum==0;
}
if(root.left!=null){
boolean left = hasPathSum(root.left, targetSum);
if (left) {// 已经找到
return true;
}
//return hasPathSum(root.left,targetSum); 不对
}
if(root.right!=null){
boolean right = hasPathSum(root.right, targetSum);
if (right) {// 已经找到
return true;
}
} //return hasPathSum(root.right,targetSum);不对
return false;
}
}
113.路径总和ii
3. 从中序与后序遍历序列构造二叉树(106) 105.从前序与中序遍历序列构造二叉树
- 题目链接:
- 文章讲解/视频讲解:https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html