首页 > 编程语言 >算法——树(二)

算法——树(二)

时间:2023-06-15 20:15:11浏览次数:30  
标签:right return 算法 ans null root left

1、路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。

 1 class Solution {
 2     boolean haspath=false;
 3     public boolean hasPathSum(TreeNode root, int targetSum) {
 4         if(root==null)return false;
 5         else{
 6             if(root.left==null&&root.right==null){
 7                 return root.val==targetSum;
 8             }
 9             return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
10         }
11     }
12 
13 }
View Code

2、翻转二叉树

 1 class Solution {
 2     public TreeNode invertTree(TreeNode root) {
 3         if(root==null)return root;
 4         TreeNode tmp=root.left;
 5         root.left=root.right;
 6         root.right=tmp;
 7         root.left=invertTree(root.left);
 8         root.right=invertTree(root.right);
 9         return root;
10 
11     }
12 }
View Code

3、二叉树的所有路径

bfs

 1 //bfs
 2 class Solution {
 3     public List<String> binaryTreePaths(TreeNode root) {
 4         
 5         List<String> ans=new ArrayList<>();
 6         if(root==null)return ans;
 7         Queue<TreeNode> queue=new ArrayDeque<>();
 8         Queue<String> paths=new ArrayDeque<>();
 9         queue.add(root);
10         paths.add(Integer.toString(root.val));
11         while(!queue.isEmpty()){
12             TreeNode tmp=queue.poll();
13             String path=paths.poll();
14             if(tmp.left==null&&tmp.right==null){
15                 ans.add(path);
16             }else{
17                 if(tmp.left!=null){
18                     paths.offer(new StringBuffer(path).append("->").append(tmp.left.val).toString());
19                     queue.offer(tmp.left);
20                 }
21                 if(tmp.right!=null){
22                     paths.offer(new StringBuilder(path).append("->").append(tmp.right.val).toString());
23                     queue.offer(tmp.right);
24                 }
25             }
26         }
27         return ans;
28 
29     }
30 }
View Code

dfs递归:

 1 //dfs
 2 class Solution {
 3     public List<String> binaryTreePaths(TreeNode root) {
 4         
 5         List<String> ans=new ArrayList<>();
 6         if(root==null)return ans;
 7         dfs(root,ans,"");
 8         return ans;
 9     }
10     public void dfs(TreeNode root,List<String> ans,String path){
11         if(root!=null){
12             StringBuilder sb=new StringBuilder(path);
13             sb.append(root.val);
14             if(root.left==null&& root.right==null){
15                 ans.add(sb.toString());
16             }            
17             sb.append("->");
18             dfs(root.left,ans,sb.toString());
19             dfs(root.right,ans,sb.toString());
20 
21         }
22     } 
23 }
View Code

dfs 栈:

 1 class Solution {
 2     public List<String> binaryTreePaths(TreeNode root) {
 3         
 4         List<String> ans=new ArrayList<>();
 5         if(root==null)return ans;
 6         Deque<TreeNode> stack=new LinkedList<>();
 7         Deque<String> paths=new LinkedList<>();
 8         stack.push(root);
 9         paths.push(Integer.toString(root.val));
10         while(!stack.isEmpty()){
11             TreeNode node=stack.pop();
12             String path=paths.pop();
13             if(node.left==null&&node.right==null){
14                 ans.add(path);
15             }
16             if(node.left!=null){
17                 stack.push(node.left);
18                 paths.push(new StringBuilder(path).append("->").append(node.left.val).toString());
19             }
20             if(node.right!=null){
21                 stack.push(node.right);
22                 paths.push(new StringBuilder(path).append("->").append(node.right.val).toString());
23             }
24         }
25         return ans;
26     }
27 
28 }
View Code

4、左叶子之和

 1 class Solution {
 2     int result = 0;
 3     public int sumOfLeftLeaves(TreeNode root) {
 4         if (root == null) {
 5             return 0;
 6         }
 7         dfs(root, 0);
 8         return result;
 9     }
10 
11     void dfs(TreeNode root, int direction) {
12         if (root == null) {
13             return;
14         }
15         if (direction == 1 && root.left == null && root.right == null) {
16             result += root.val;
17         }
18         // 1:向左, 2:向右
19         dfs(root.left,  1);
20         dfs(root.right, 2);
21     }
22 }
View Code

5、合并二叉树

 1 class Solution {
 2     public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
 3         if(root1==null&&root2==null){
 4             return null;
 5         }else{
 6             if(root1==null)return root2;
 7             if(root2==null)return root1;
 8             else{
 9                 root1.val=root1.val+root2.val;
10                 root1.left=mergeTrees(root1.left,root2.left);
11                 root1.right=mergeTrees(root1.right,root2.right);
12                 return root1;
13             }
14         }
15 
16     }
17 }
View Code

6、N叉树的最大高度

 1 class Solution {
 2     public int maxDepth(Node root) {
 3         if(root==null)return 0;
 4         int max=0;
 5         for(Node child:root.children){
 6             max=Math.max(maxDepth(child),max);
 7         }
 8         return max+1;
 9         
10     }
11 }
View Code

 

标签:right,return,算法,ans,null,root,left
From: https://www.cnblogs.com/coooookie/p/17483974.html

相关文章

  • 【学习笔记】Primal-Dual 原始对偶算法
    Johnson全源最短路算法Floyd可以\(O(n^3)\)处理全源最短路,Bellman-Ford单源最短路的复杂度是\(O(nm)\)的,Dijkstra可以做到\(O(m\logm)\)但不能处理负边权,所以Johnson全源最短路算法通过处理使得可以用\(n\)次Dijkstra解决有负权图的全源最短路。先建超级源点,向......
  • 算法练习-day8
    字符串28.找出字符串中第一个匹配项的下标题意:给你两个字符串haystack和needle,请你在haystack字符串中找出needle字符串的第一个匹配项的下标(下标从0开始)。如果needle不是haystack的一部分,则返回-1。示例:    思路:本题有两种思路:1.暴力求解法,只需要一次遍历,以i为haystack字......
  • 算法——树(一)
    1、中序遍历递归classSolution{List<Integer>ans=newArrayList<>();publicList<Integer>inorderTraversal(TreeNoderoot){inorder(root);returnans;}publicvoidinorder(TreeNoderoot){if(root!=nul......
  • 数据结构(python版)—— 2、前期知识与算法分析
    从C转到python(一)C:helloWorld!#include<stdio.h>​intmain(){//sayhelloprintf("HelloWorld!\n")}1-Compile编译到机器码2-Link与各种库链接3-Execute执行目标程序Python:HelloWorld!defmain():#sayhelloprint("HelloWorld!"......
  • 力扣上任务调度相关的算法
    目录应用应用1:Leetcode1834.单线程CPU题目分析代码实现应用2:Leetcode621.任务调度器题目分析代码实现应用应用1:Leetcode1834.单线程CPU题目1834.单线程CPU给你一个二维数组tasks,用于表示n项从0到n-1编号的任务。其中\(tasks[i]=[enqueueTime_i,proc......
  • 优化算法——人工蜂群算法(ABC)
    一、人工蜂群算法的介绍  人工蜂群算法(ArtificialBeeColony,ABC)是由Karaboga于2005年提出的一种新颖的基于群智能的全局优化算法,其直观背景来源于蜂群的采蜜行为,蜜蜂根据各自的分工进行不同的活动,并实现蜂群信息的共享和交流,从而找到问题的最优解。人工蜂群算法属于群......
  • 简单易学的机器学习算法——岭回归(Ridge Regression)
    一、一般线性回归遇到的问题  在处理复杂的数据的回归问题时,普通的线性回归会遇到一些问题,主要表现在:预测精度:这里要处理好这样一对为题,即样本的数量和特征的数量时,最小二乘回归会有较小的方差时,容易产生过拟合时,最小二乘回归得不到有意义的结果模型的解释能力:如果模型中的特征......
  • 简单易学的机器学习算法——协同过滤推荐算法(1)
    一、推荐系统的概念  推荐系统(RecommendationSystem,RS),简单来说就是根据用户的日常行为,自动预测用户的喜好,为用户提供更多完善的服务。举个简单的例子,在京东商城,我们浏览一本书之后,系统会为我们推荐购买了这本书的其他用户购买的其他的书:推荐系统在很多方面都有很好的应......
  • C#中使用CAS实现无锁算法
    CAS的基本概念CAS(Compare-and-Swap)是一种多线程并发编程中常用的原子操作,用于实现多线程间的同步和互斥访问。它操作通常包含三个参数:一个内存地址(通常是一个共享变量的地址)、期望的旧值和新值。CompareAndSwap(内存地址,期望的旧值,新值)CAS操作会比较内存地址处的值与期望......
  • 高效的二进制取模算法
    限制必须是长度必须是2的指数直接取指数的低位长度算法演示长度为80b000(0)0b001(1)0b010(2)0b011(3)0b100(4)0b101(5)0b110(6)0b11(7)13二进制0x110113mod8=55的二进制1012^3=8直接取0x1101后三位101使用场景布谷鸟过滤器还有一种就......