Day17代码随想录
110.平衡二叉树
1、题目描述
给定一个二叉树,判断它是否是
平衡二叉树
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:
输入:root = []
输出:true
2.解题思路
判断左右子树高度相差是不是小于等于1,然后利用递归进行前序遍历,判断左子树是否为平衡二叉树,在判断右子树是否为平衡二叉树
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return isBalanced(root.left)&&isBalanced(root.right)&&Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1;
}
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
257.二叉树的所有路径
1.题目描述
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]
示例 2:
输入:root = [1]
输出:["1"]
提示:
- 树中节点的数目在范围
[1, 100]
内 -100 <= Node.val <= 100
2.解题思路及代码实现
利用递归+回溯实现,采用前序遍历,先将该结点的val加入到path中,并判断该结点是否为叶子结点,如果为叶子结点将,处理path为要求的格式并加入到res中,并递归处理左子树,右子树,处理完左右子树要进行回溯。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root==null) return res;
List<Integer> path = new ArrayList<>();
deal(root,path,res);
return res;
}
public void deal(TreeNode root,List<Integer> path ,List<String> res){
path.add(root.val);
if (root.left==null&&root.right==null){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size()-1; i++) {
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size()-1));
res.add(sb.toString());
return;
}
if (root.left!=null){
deal(root.left,path,res);
path.remove(path.size()-1);
}
if (root.right!=null){
deal(root.right,path,res);
path.remove(path.size()-1);
}
}
}
202.左子树之和
1.题目描述
给定二叉树的根节点 root
,返回所有左叶子之和。
示例 1:
输入: root = [3,9,20,null,null,15,7]
输出: 24
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
示例 2:
输入: root = [1]
输出: 0
2.解题思路及代码实现
1.递归
递归求左子树的左叶子结点个数,在求右子树的左叶子结点个数
前中后序遍历都可以,本样例采用后续遍历,判断一个节点是否为左叶子结点,需要根据其父节点判断,如果父节点有左孩子,且左孩子为叶子结点,那么就为左叶子结点
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null) return 0;
int sumleft = sumOfLeftLeaves(root.left);
int sumright = sumOfLeftLeaves(root.right);
int count = 0;
if (root.left!=null&&root.left.left==null&&root.left.right==null){
count+=root.left.val;
}
return count+sumleft+sumright;
}
}
2.dfs深度优先遍历
不断往下走,并不断判断,如果是向左边深度遍历则判断是不是叶子结点,向右边深度遍历不用判断
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root==null)return 0;
return dfs(root);
}
public int dfs(TreeNode root){
int count = 0;
if (root.left!=null){
if (isLeafNode(root.left))
count+=root.left.val;
else
count+=dfs(root.left);
}
if (root.right!=null){
count+=dfs(root.right);
}
return count;
}
public boolean isLeafNode(TreeNode node){
if (node.left==null&&node.right==null)
return true;
else
return false;
}
}