LeetCode-222,110,257,404:
222. 完全二叉树的节点个数
110.平衡二叉树
257. 二叉树的所有路径
404. 左叶子之和
第一题:
递归实现即可:
class Solution {
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
return countNodes(root.left)+countNodes(root.right)+1;
}
}
第二题:
依然是递归实现
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
return isBalanced(root.left) && isBalanced(root.right) && Math.abs(getDepth(root.left)-getDepth(root.right))<=1;
}
public int getDepth(TreeNode root){
if(root==null){
return 0;
}
return Math.max(getDepth(root.left),getDepth(root.right))+1;
}
}
第三题:
依然是递归,意外跑通了,用StringBuilder可能快一点?
class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
String temp = "";
getRoad(root,temp);
return res;
}
public void getRoad(TreeNode root,String temp){
if(root==null){
return;
}
if(root.left==null && root.right==null){
temp = temp+root.val;
res.add(temp);
temp = "";
return;
}
temp = temp+root.val+"->";
getRoad(root.left,temp);
getRoad(root.right,temp);
}
}
第四题:
BFS:一开始报错,原因是这里需要计算的是左叶子节点,而非左子节点,需要判断是否是叶子节点。
设置了两个队列:一个用来存储节点,index队列用来判断是否为左子节点,好像多此一举了,可以进行优化
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
int sum = 0;
Queue<TreeNode> q = new LinkedList<>();
// 0为左,1为右
Queue<Integer> index = new LinkedList<>();
q.add(root);
index.add(1);
while(!q.isEmpty()){
int size = q.size();
TreeNode node = q.poll();
if(index.poll()==0 && node.left==null && node.right==null){
sum+=node.val;
}
if(node.left!=null){
q.add(node.left);
index.add(0);
}
if(node.right!=null){
q.add(node.right);
index.add(1);
}
size--;
}
return sum;
}
}
优化后:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
int sum = 0;
Queue<TreeNode> q = new LinkedList<>();
// 0为左,1为右
q.add(root);
while(!q.isEmpty()){
int size = q.size();
TreeNode node = q.poll();
if (node.left != null) { // 左节点不为空
q.add(node.left);
if (node.left.left == null && node.left.right == null){
sum += node.left.val;
}
}
if(node.right!=null){
q.add(node.right);
}
size--;
}
return sum;
}
}
DFS:尝试一下
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
getResult(root);
return sum;
}
public void getResult(TreeNode root){
if(root==null){
return;
}
if(root.left!=null && root.left.left==null && root.left.right==null){
sum+=root.left.val;
}
getResult(root.left);
getResult(root.right);
}
}