7月16日,二叉树进阶习题

hello大家好呀,本博客目的在于记录暑假学习打卡,后续会整理成一个专栏,主要打算在暑假学习完数据结构,因此会发一些相关的数据结构实现的博客和一些刷的题,个人学习使用,也希望大家多多支持,有不足之处也请指出,谢谢大家。

一,二叉树的层序遍历

yi-li-ya-vn - 力扣(LeetCode)

二叉树层序遍历需要用到队列,当队列不为空,每次拿出一个节点,如果它的子节点不为空,则入队列,这样便能实现层层遍历,先看基础版本

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;
    }
}

二,叉树最近的公共祖先

. - 力扣(LeetCode)

想要理解这题,我们需要分清可能的四种情况

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;
    }
}

本篇博客就到这里,感谢观看

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值