代码学习记录15

随想录日记part15

t i m e : time: time 2024.03.09



主要内容:今天的主要内容是二叉树的第四部分,主要涉及平衡二叉树的建立;二叉树的路径查找;左叶子之和;找树左下角的值;路径总和;构造二叉树。



Topic1平衡二叉树

题目: 给定一个二叉树,判断它是否是平衡二叉树。

示例:
请添加图片描述

输入: r o o t = [ 3 , 9 , 20 , n u l l , n u l l , 15 , 7 ] root = [3,9,20,null,null,15,7] root=[3,9,20,null,null,15,7]
输出: t r u e true true

思路: 首先我们得清楚以下概念:
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。
l e e t c o d e leetcode leetcode 中强调的深度和高度很明显是按照节点来计算的,如图:

下面给出递归的写法:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null)return true;
        return deepth(root)!=-1;
    }
    // -1 表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度
    private int deepth(TreeNode root){
        //这里有个大坑就是子树也必须是平衡二叉树
        //递归出口
        if(root==null)return 0;
        //单层递归的逻辑
        int left=deepth(root.left);
        if(left==-1) return -1;
        int right=deepth(root.right);
        if(right==-1)return -1;
        if(Math.abs(left-right)>1)return -1;
        else return 1+Math.max(left,right);
    }
}


Topic2二叉树的所有路径

题目: 给你一个二叉树的根节点 r o o t root root ,按任意顺序返回所有从根节点到叶子节点的路径。(叶子节点是指没有子节点的节点。)
示例:请添加图片描述

输入: r o o t = [ 1 , 2 , 3 , n u l l , 5 ] root = [1,2,3,null,5] root=[1,2,3,null,5]
输出: [ “ 1 − > 2 − > 5 " , “ 1 − > 3 ” ] [“1->2->5",“1->3”] [“1>2>5",“1>3”]

思路:
这道题目要求从根节点到叶子的路径,所以需要前序遍历,这样才方便让父节点指向孩子节点,找到对应的路径。在这道题目中将第一次涉及到回溯,因为我们要把路径记录下来,需要回溯来回退一个路径再进入另一个路径。
前序遍历以及回溯的过程如图:

  • 递归法:
class Solution {

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        if (root == null)
            return result;
        List<Integer> tem = new ArrayList<Integer>();
        search(root, tem, result);
        return result;

    }

    private void search(TreeNode root, List<Integer> tem, List<String> s) {
        tem.add(root.val);// 中
        // 递归出口
        if (root.left == null && root.right == null) {
            StringBuilder te = new StringBuilder();
            for (int i = 0; i < tem.size() - 1; i++) {
                te.append(tem.get(i)).append("->");
            }
            te.append(tem.get(tem.size() - 1));
            s.add(te.toString());
        }
        if (root.left != null) {//左
            search(root.left, tem, s);
            tem.remove(tem.size() - 1);
        }
        if (root.right != null) {//右
            search(root.right, tem, s);
            tem.remove(tem.size() - 1);
        }
    }
}


Topic3左叶子之和数

题目: 给定二叉树的根节点 root ,返回所有左叶子之和。
示例:
请添加图片描述

输入: r o o t = [ 3 , 9 , 20 , n u l l , n u l l , 15 , 7 ] root = [3,9,20,null,null,15,7] root=[3,9,20,null,null,15,7]
输出: 24 24 24

思路:

递归法:递归的遍历顺序为后序遍历(左右中)

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null)
            return 0;
        if (root.left == null)
            return sumOfLeftLeaves(root.right);
        else {
            if (root.left.left == null && root.left.right == null)
                return root.left.val + sumOfLeftLeaves(root.right);
            else {
                return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
            }
        }
    }
}


Topic4找树左下角的值

题目: 给定一个二叉树的 根节点 r o o t root root,请找出该二叉树的最底层最左边节点的值。
假设二叉树中至少有一个节点。
示例:
请添加图片描述

输入: [ 1 , 2 , 3 , 4 , n u l l , 5 , 6 , n u l l , n u l l , 7 ] [1,2,3,4,null,5,6,null,null,7] [1,2,3,4,null,5,6,null,null,7]
输出: 7 7 7

思路:
递归:可以使用前序遍历(当然中序,后序都可以,因为本题没有中间节点的处理逻辑,只要左优先就行),保证优先左边搜索,然后记录深度最大的叶子节点,此时就是树的最后一行最左边的值。

class Solution {
    private int result = 0;
    private int depth = -1;
    public int findBottomLeftValue(TreeNode root) {
        result = root.val;
        findLeft(root, 0);
        return result;
    }
    private void findLeft(TreeNode root, int deep) {
        if (root == null)
            return;
        if (root.left == null && root.right == null) {
            if (deep > depth) {
                result = root.val;
                depth = deep;
            }
        }
        if (root.left != null)
            findLeft(root.left, deep + 1);
        if (root.right != null)
            findLeft(root.right, deep + 1);
    }
}

迭代法:使用层序遍历,直接输出最后每一轮的第一个元素即可。

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> que = new LinkedList<>();
        if (root != null)
            que.offer(root);
        int result = 0;
        while (!que.isEmpty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = que.poll();
                if (i == 0)
                    result = node.val; // 记录最后一行第一个元素
                if (node.left != null)
                    que.offer(node.left);
                if (node.right != null)
                    que.offer(node.right);
            }
        }
        return result;
    }
}


Topic5路径总和

题目: 给你二叉树的根节点 r o o t root root 和一个表示目标和的整数 t a r g e t S u m targetSum targetSum 。判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和 t a r g e t S u m targetSum targetSum 。如果存在,返回 t r u e true true ;否则,返回 f a l s e false false
叶子节点是指没有子节点的节点。
示例:
外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

输入: r o o t = [ 5 , 4 , 8 , 11 , n u l l , 13 , 4 , 7 , 2 , n u l l , n u l l , n u l l , 1 ] , t a r g e t S u m = 22 root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 root=[5,4,8,11,null,13,4,7,2,null,null,null,1],targetSum=22
输出: t r u e true true

思路:

可以使用深度优先遍历的方式来遍历二叉树,
1.确定递归函数的参数和返回类型
参数:需要二叉树的根节点
计数器:用来计算二叉树的一条边之和是否正好是目标和
返回值:递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:

  • 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(这种情况就是本文下半部分介绍的113.路径总和ii)
  • 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。 (这种情况我们在236. 二叉树的最近公共祖先 (opens new window)中介绍)
  • 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。(本题的情况)

而本题要找一条符合条件的路径,所以递归函数需要返回值,及时返回,那么返回类型是什么:
在这里插入图片描述
图中可以看出,遍历的路线,并不要遍历整棵树,所以递归函数需要返回值,可以用 b o o l bool bool 类型表示
2.确定终止条件
计数器统计一条路径的和:
用递减,让计数器count初始为目标和,然后每次减去遍历路径节点上的数值。如果最后 c o u n t = 0 count=0 count=0,同时到了叶子节点的话,说明找到了目标和。如果遍历到了叶子节点, c o u n t count count 不为 0 0 0,就是没找到。
3.确定单层递归的逻辑
因为终止条件是判断叶子节点,所以递归的过程中就不要让空节点进入递归了。递归函数是有返回值的,如果递归函数返回 t r u e true true,说明找到了合适的路径,应该立刻返回。

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null)
            return false;
        return ifchecked(root, targetSum - root.val);
    }

    private boolean ifchecked(TreeNode root, int count) {
        // 递归出口
        if (root.left == null && root.right == null && count == 0)
            return true;
        if (root.left == null && root.right == null)
            return false;
        if (root.left != null) {
            count = count - root.left.val;
            if (ifchecked(root.left, count))
                return true;
            count = count + root.left.val;
        }
        if (root.right != null) {
            count = count - root.right.val;
            if (ifchecked(root.right, count))
                return true;
            count = count + root.right.val;
        }
        return false;
    }
}


Topic6构造二叉树

题目: 给定两个整数数组 i n o r d e r inorder inorder p o s t o r d e r postorder postorder ,其中 i n o r d e r inorder inorder 是二叉树的中序遍历, p o s t o r d e r postorder postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
示例:
外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

输入: i n o r d e r = [ 9 , 3 , 15 , 20 , 7 ] , p o s t o r d e r = [ 9 , 15 , 7 , 20 , 3 ] inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] inorder=[9,3,15,20,7],postorder=[9,15,7,20,3]
输出: [ 3 , 9 , 20 , n u l l , n u l l , 15 , 7 ] [3,9,20,null,null,15,7] [3,9,20,null,null,15,7]

思路:

看两个序列,画一棵二叉树的话,应该分分钟都可以画出来。
流程如图:
在这里插入图片描述
那么代码应该怎么写呢?
应该想到了递归,一共分以下几步:

  • 1.如果数组大小为零的话,说明是空节点了。
  • 2.如果不为空,那么取后序数组最后一个元素作为节点元素。
  • 3.找到后序数组最后一个元素在中序数组的位置,作为切割点
  • 4.切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
  • 5.切割后序数组,切成后序左数组和后序右数组
  • 6.递归处理左区间和右区间
class Solution {
    Map<Integer, Integer> map;  // 方便根据数值查找位置
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置
            map.put(inorder[i], i);
        }
        return findNode(inorder,0,inorder.length,postorder,0,inorder.length);
    }
    public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd){
        //>- 1.如果数组大小为零的话,说明是空节点了。
        if(inBegin>=inEnd || postBegin>=postEnd)return null;
        // >- 2.如果不为空,那么取后序数组最后一个元素作为节点元素。
        int rootindex=map.get(postorder[postEnd-1]);
        TreeNode root=new TreeNode(inorder[rootindex]);
        // >- 3.找到后序数组最后一个元素在中序数组的位置,作为切割点 
        // >- 4.切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
        // >- 5.切割后序数组,切成后序左数组和后序右数组
        // >- 6.递归处理左区间和右区间
        int lenOfLeft = rootindex - inBegin;  // 保存中序左子树个数,用来确定后序数列的个数
        root.left=findNode(inorder,inBegin,rootindex,postorder,postBegin,postBegin+lenOfLeft);
        root.right=findNode(inorder,rootindex+1,inEnd,postorder,postBegin+lenOfLeft,postEnd-1);
        return root;
    }
}

这个代码很难写。

  • 38
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值