欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 代码随想录算法训练营Day14

代码随想录算法训练营Day14

2025/5/17 9:57:22 来源:https://blog.csdn.net/lynyzy/article/details/142601744  浏览:    关键词:代码随想录算法训练营Day14

513.找树左下角的值

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

层序遍历

class Solution {public int findBottomLeftValue(TreeNode root) {if(root==null){return 0;}Deque<TreeNode> myque=new LinkedList<>();myque.offer(root);int count=0;while(!myque.isEmpty()){count++;int len=myque.size();while(len>0){TreeNode cur=myque.poll();if(cur.left!=null){myque.offer(cur.left);}if(cur.right!=null){myque.offer(cur.right);}len--;}}int count1=1;myque.offer(root);while(count1<count){count1++;int len=myque.size();while(len>0){TreeNode cur=myque.poll();if(cur.left!=null){myque.offer(cur.left);}if(cur.right!=null){myque.offer(cur.right);}len--;}}TreeNode cur2=myque.poll();return cur2.val;}
}

112. 路径总和

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

前序递归

class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {if(root==null){return false;}List<Integer> path=new ArrayList<>();     return hasSum(root,path,targetSum);}public boolean hasSum(TreeNode root,List<Integer> path,int targetSum){path.add(root.val);if(root.left==null&&root.right==null){int sum=0;for(Integer i:path){sum+=i;}if(sum==targetSum)return true;return false;}if(root.left!=null){boolean has=hasSum(root.left,path,targetSum);if(has)return has;path.remove(path.size()-1);}if(root.right!=null){boolean has=hasSum(root.right,path,targetSum);if(has)return has;path.remove(path.size()-1);}return false;}}

106.从中序与后序遍历序列构造二叉树

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

循环不变量,前序递归

class Solution {Map<Integer,Integer> inordermap;public TreeNode buildTree(int[] inorder, int[] postorder) {inordermap=new HashMap<>();for(int i=0;i<inorder.length;i++){inordermap.put(inorder[i],i);}return fondNode(inorder,0,inorder.length,postorder,0,postorder.length);}public TreeNode fondNode(int[] inorder,int instart,int inend,int[]postorder,int poststart,int postend){if(instart>=inend||poststart>=postend){return null;}int inindex=inordermap.get(postorder[postend-1]);TreeNode root=new TreeNode(postorder[postend-1]);int leftLen=inindex-instart;root.left=fondNode(inorder,instart,inindex,postorder,poststart,poststart+leftLen);root.right=fondNode(inorder,inindex+1,inend,postorder,poststart+leftLen,postend-1);return root;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词