hello大家好呀,本博客目的在于记录暑假学习打卡,后续会整理成一个专栏,主要打算在暑假学习完数据结构,因此会发一些相关的数据结构实现的博客和一些刷的题,个人学习使用,也希望大家多多支持,有不足之处也请指出,谢谢大家。
一,二叉树的层序遍历
二叉树层序遍历需要用到队列,当队列不为空,每次拿出一个节点,如果它的子节点不为空,则入队列,这样便能实现层层遍历,先看基础版本
class Solution {
public void levelOrder(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
System.out.println(cur.val+" ");
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
}
}
当然,对于这题,还需要一个链表模拟的二维数组,来接收val值
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret=new ArrayList<>();
if(root==null) {
return ret;
}
Queue<TreeNode> queue=new LinkedList();
queue.add(root);
while(!queue.isEmpty()){
int size=queue.size();
List<Integer> list=new ArrayList<>();
while(size!=0){
TreeNode cur=queue.poll();
list.add(cur.val);
if(cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
size--;}
ret.add(list);
}
return ret;
}
}
二,叉树最近的公共祖先
想要理解这题,我们需要分清可能的四种情况
1,p或q为root点,那么root为公共祖先
2,q和p分别在root两边,那么root为公共节点
3,q和p在root一侧,但是在同一个节点左右
4,q和p在root一侧,但是不在同一个节点左右
根据思路写代码会轻松很多
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
if(p==root||q==root){
return root;
}
TreeNode Left=lowestCommonAncestor(root.left,p,q);
TreeNode Right=lowestCommonAncestor(root.right,p,q);
if(Left==p&&Right==q){
return root;
}
if(Left==null){
return Right;
}
if(Right==null){
return Left;
}
return root;
}
}
本篇博客就到这里,感谢观看