当前位置: 首页 > news >正文

代码随想录算法训练营Day13

110.平衡二叉树

力扣题目链接:. - 力扣(LeetCode)

后序迭代

class Solution {public boolean isBalanced(TreeNode root) {return getHeight(root)!=-1;}public int getHeight(TreeNode root){if(root==null){return 0;}int leftheight=getHeight(root.left);int rightheith=getHeight(root.right);if(leftheight==-1||rightheith==-1){return -1;}else if(Math.abs(leftheight-rightheith)>1){return -1;  }return Math.max(leftheight,rightheith)+1;}
}

257. 二叉树的所有路径

力扣题目链接:. - 力扣(LeetCode)

前序递归

class Solution {public List<String> binaryTreePaths(TreeNode root) {List<String> res=new ArrayList<>();if(root==null){return res;}List<Integer> pathnode=new ArrayList<>();bianli(root,res,pathnode);return res;}public void bianli(TreeNode root,List<String> res,List<Integer> pathnode){pathnode.add(root.val);if(root.left==null&&root.right==null){StringBuilder str=new StringBuilder();for(int i=0;i<pathnode.size()-1;i++){str.append(pathnode.get(i)).append("->");}str.append(pathnode.get(pathnode.size()-1));res.add(str.toString());return;}if(root.left!=null){bianli(root.left,res,pathnode);if(!pathnode.isEmpty()){pathnode.remove(pathnode.size()-1);}       }if(root.right!=null){bianli(root.right,res,pathnode);if(!pathnode.isEmpty()){pathnode.remove(pathnode.size()-1);}     }return;}
}

404.左叶子之和

力扣题目链接:. - 力扣(LeetCode)

后序递归

class Solution {public int sumOfLeftLeaves(TreeNode root) {if(root==null){return 0;}int rightsum=sumOfLeftLeaves(root.right);int leftsum=sumOfLeftLeaves(root.left);int midsum=0;if(root.left!=null&&root.left.left==null&&root.left.right==null){midsum=root.left.val;}int sum=midsum+rightsum+leftsum;return sum;}
}

222.完全二叉树的节点个数

力扣题目链接:. - 力扣(LeetCode)

层序遍历

class Solution {public int countNodes(TreeNode root) {if(root==null){return 0;}Deque<TreeNode> myque=new LinkedList<>();myque.offer(root);int sum=0;int res=0;while(!myque.isEmpty()){sum++;int len=myque.size();res+=len;if(len!=Math.pow(2,sum-1))break;while(len>0){TreeNode cur=myque.poll();if(cur.left!=null){myque.offer(cur.left);}if(cur.right!=null){myque.offer(cur.right);}len--;}}return res;}
}


http://www.mrgr.cn/news/37696.html

相关文章:

  • SSL证书自动申请脚本
  • java 生成.h文件,java调用c语言dll动态链接库流程
  • Power Platform开发小技巧,一天一个APP, 如何快速搭建二维码识别器
  • 传奇GEE引擎版本如何封挂?GEE引擎设置简单的封挂脚本教程
  • Java8 IntStream流sum的Bug
  • Go语言开发后台框架不能只有CRUD还需有算法集成基础功能-GoFly框架集成了自然语言处理(NLP)分词、关键词提取和情感分析
  • 「JavaScript深入」聊一聊 new操作符具体干了什么?
  • 基于keras 的神经网络股价预测模型
  • 2024/9/27刷题记录(cf1800 - 2000)
  • 数据工程师岗位常见面试问题-1(附回答)
  • QML使用Qt自带软键盘例子
  • Rust SQLite 跨平台使用
  • 《向量数据库指南》——非结构化数据迁移服务的核心能力
  • `pattern = r“(\d+)(CNY|JPY|HKD|EUR|GBP|fen|cents|sen|eurocents|pence)“
  • 选择更轻松:山海鲸可视化与PowerBI的深度对比
  • idea插件通义灵码
  • CUDAExample: 波纹示例
  • 敏感字段加密 - 华为OD统一考试(E卷)
  • 了解网络的相关信息
  • 环形链表的约瑟夫问题