算法训练营day18|513.找树左下角的值,112.路径总和,113路径总和II,106.从中序与后序遍历构造二叉树,105.从前序与中序遍历构造二叉树

知识点

刷题

513.找树左下角的值

LeetCode连接 513. 找树左下角的值 - 力扣(LeetCode)

题目描述

方法1:bfs+队列

层序遍历每一层,记录第一个数字,最后一层就是题目所求

package daimasuixiangshuati.day18_erchashu;

import java.util.LinkedList;

/**
 * @Author LeiGe
 * @Date 2023/11/9
 * @Description todo
 */
public class ZhaoShuZuoXiaJiaoDeZhi513_1 {
    /**
     * 方法1:bfs-队列
     * 0.最后一层的最左边的值就是整个树的左下角的值
     *
     * @param root
     * @return
     */
    public int findBottomLeftValue(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.addLast(root);
        int result = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.pollFirst();
                if (i == 0) {
                    result = node.val;
                }
                if (node.left != null) {
                    queue.addLast(node.left);
                }
                if (node.right != null) {
                    queue.addLast(node.right);
                }
            }
        }
        return result;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

方法2:dfs+递归

package daimasuixiangshuati.day18_erchashu;

import java.util.LinkedList;

/**
 * @Author LeiGe
 * @Date 2023/11/9
 * @Description todo
 */
public class ZhaoShuZuoXiaJiaoDeZhi513_2 {
    /**
     * 方法2:dfs-递归
     * 保证优先搜索左子树,拿到的是左下角的值
     *
     * @param root
     * @return
     */
    int maxDepth = -1;
    int result;

    public int findBottomLeftValue(TreeNode root) {
        dfs(root, 0);
        return result;
    }

    private void dfs(TreeNode root, int depth) {

        //baseCase 叶子节点,更新最大深度,获得值
        if (root.left == null && root.right == null) {
            if (depth > maxDepth) {
                maxDepth = depth;
                result = root.val;
            }
            return;
        }

        if (root.left != null) {
            depth++;
            dfs(root.left, depth);
            depth--;// 回溯
        }

        if (root.right != null) {
            depth++;
            dfs(root.right, depth);
            depth--;// 回溯
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

112.路径总和

LeetCode连接 112. 路径总和 - 力扣(LeetCode)

题目描述

方法1:dfs+递归

package daimasuixiangshuati.day18_erchashu;

/**
 * @Author LeiGe
 * @Date 2023/11/9
 * @Description todo
 */
public class LuJingZongHe112_1 {

    /**
     * 方法1:dfs-递归
     * 1.前序遍历
     *
     * @param root
     * @param targetSum
     * @return
     */
    public boolean hasPathSum(TreeNode root, int targetSum) {
        return dfs(root, targetSum);
    }

    private boolean dfs(TreeNode root, int targetSum) {
        //baseCase
        if (root == null) {
            return false;
        }

        //如果到达了叶子节点,判断和是否等于targetSum
        if (root.left == null && root.right == null) {
            return root.val == targetSum;
        }

        //如果左右子树是否符合条件,如果有一个树符合条件则符合条件
        boolean left = dfs(root.left, targetSum - root.val);
        boolean right = dfs(root.right, targetSum - root.val);

        return left || right;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

方法2:dfs+递归+回溯

package daimasuixiangshuati.day18_erchashu;

/**
 * @Author LeiGe
 * @Date 2023/11/9
 * @Description todo
 */
public class LuJingZongHe112_2 {

    /**
     * 方法2:dfs-递归-体现回溯过程
     * 1.前序遍历
     *
     * @param root
     * @param targetSum
     * @return
     */
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        return dfs2(root, targetSum - root.val);
    }

    private boolean dfs2(TreeNode root, int targetSum) {

        // 如果到叶子节点,判断targetSum是否等于0
        if (root.left == null && root.right == null) {
            return targetSum == 0;
        }

        // 左
        if (root.left != null) {
            targetSum = targetSum - root.left.val;
            // 递归,处理节点;
            boolean left = dfs2(root.left, targetSum);
            if (left) {
                return true;
            }
            // 回溯,撤销处理结果
            targetSum = targetSum + root.left.val;
        }

        // 右
        if (root.right != null) {
            targetSum = targetSum - root.right.val;
            // 递归,处理节点;
            boolean right = dfs2(root.right, targetSum);
            if (right) {
                return true;
            }
            // 回溯,撤销处理结果
            targetSum = targetSum + root.right.val;
        }
        return false;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

方法3:dfs+栈

package daimasuixiangshuati.day18_erchashu;

import java.util.Stack;

/**
 * @Author LeiGe
 * @Date 2023/11/9
 * @Description todo
 */
public class LuJingZongHe112_3 {

    /**
     * 方法2:dfs-栈
     * 1.前序遍历
     *
     * @param root
     * @param targetSum
     * @return
     */
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }

        Stack<Node> st = new Stack<>();
        st.push(new Node(root, root.val));

        while (!st.isEmpty()) {
            Node node = st.pop();

            //叶子节点
            if (node.treeNode.left == null && node.treeNode.right == null) {
                // 找到了一条符合的路径
                if(node.sum==targetSum){
                    return true;
                }
            }

            // 右子节点,压入节点的时候,将该节点的路径和记录下来
            if (node.treeNode.right != null) {
                st.push(new Node(node.treeNode.right, node.sum + node.treeNode.right.val));
            }

            // 左子节点,压入节点的时候,将该节点的路径和记录下来
            if (node.treeNode.left != null) {
                st.push(new Node(node.treeNode.left, node.sum + node.treeNode.left.val));
            }
        }

        return false;
    }

    public class Node {
        TreeNode treeNode;
        int sum;

        public Node(TreeNode treeNode, int sum) {
            this.treeNode = treeNode;
            this.sum = sum;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

113.路径总和II

LeetCode连接 113. 路径总和 II - 力扣(LeetCode)

题目描述

方法1:dfs+回溯

package daimasuixiangshuati.day18_erchashu;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author LeiGe
 * @Date 2023/11/9
 * @Description todo
 */
public class LuJingZongHe113II_1 {

    /**
     * 方法1:复杂版--dfs-递归:体现回溯
     * 0.如果是遍历整个树,递归函数不用返回值,如果是遍历部分,递归函数需要返回值
     * 1.先序遍历
     * 2.用path记录当前的走过的路径,注意回溯
     *
     * @param root
     * @param targetSum
     * @return
     */
    ArrayList<List<Integer>> result = new ArrayList<>();
    ArrayList<Integer> path = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return result;
        }
        //当前节点加入到path中
        path.add(root.val);
        dfs(root, targetSum - root.val);
        return result;
    }

    private void dfs(TreeNode root, int targetSum) {

        //如果是子节点
        if (root.left == null && root.right == null) {
            //如果找到了和为sum的路径,这条路径加入到result中
            if (targetSum == 0) {
                result.add(new ArrayList<>(path));
            }
            return;
        }

        //左子树不为空
        if (root.left != null) {
            path.add(root.left.val);

            //递归
            targetSum -= root.left.val;
            dfs(root.left, targetSum);

            //回溯
            targetSum += root.left.val;
            path.remove(path.size() - 1);
        }

        //右子树不为空
        if (root.right != null) {
            path.add(root.right.val);
            targetSum -= root.right.val;

            //递归
            dfs(root.right, targetSum);

            //回溯
            targetSum += root.right.val;
            path.remove(path.size() - 1);
        }
        return;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

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

LeetCode连接 106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

题目描述

方法1:递归

后序数组的最后一个元素就是中序数组的分割点(根节点)

package daimasuixiangshuati.day18_erchashu;

/**
 * @Author LeiGe
 * @Date 2023/11/12
 * @Description todo
 */
public class CongZhongXuYuHouXuBianliXuLieGouZaoErChaShu106_1 {
    /**
     * 方法1:dfs-递归
     * 1.先从后序数组中最后一个位置找到根节点
     * 2.创建根节点
     * 3.再在中序数组中找到根节点索引,根据跟节点索引划分左子树区间,右子树区间
     * 4.根据步骤2,划分后序数组的左子树区间,右子树区间
     *  注意中序数组的大小和后序数组的大小是一样大的,所以后序数组可以通过中序数组的大小计算出
     * 4.递归得到左子树,右子树
     * 注意:所有区间都是:左闭右闭
     *
     * @param inorder
     * @param postorder
     * @return
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return dfs(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    /**
     * @param inorder   中序数组
     * @param inLeft    中序数组左边界
     * @param inRight   中序数组右边界
     * @param postorder 后序数组
     * @param postLeft  后序数组左边界
     * @param postRight 后序数组右边界
     * @return
     */
    private TreeNode dfs(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight) {
        //baseCase
        if (inRight - inLeft < 0) {
            return null;
        }
        if (inRight - inLeft == 0) {
            return new TreeNode(inorder[inLeft]);
        }
        //后序数组的最后一个就是中序数组的分割点(根节点)
        int rootVal = postorder[postRight];
        TreeNode root = new TreeNode(rootVal);
        //在中序数组中寻找根节点所在位置
        int rootIndex = findMidIndex(inorder, inLeft, inRight, rootVal);
        //根据rootIndex划分左右子树
        //中序数组:
        //左子树区间:[inLeft,rootIndex-1] 右子树区间:[rootIndex+1,inRight]
        //后序数组:
        //左子树区间:[posLeft,posLeft+(rootIndex-inLeft)-1]  右子树区间:[postLeft+(rootIndex-inLeft),poRight-1]

        //获取左子树
        TreeNode leftNode = dfs(inorder, inLeft, rootIndex - 1, postorder, postLeft, postLeft + (rootIndex - inLeft - 1));
        //获取右子树
        TreeNode rightNode = dfs(inorder, rootIndex + 1, inRight, postorder, postLeft + (rootIndex - inLeft), postRight - 1);

        //返回此节点
        root.left = leftNode;
        root.right = rightNode;
        return root;
    }

    /**
     * 在中序数组中找到根节点所在的索引
     *
     * @param inorder
     * @param left
     * @param right
     * @param target
     * @return
     */
    private int findMidIndex(int[] inorder, int left, int right, int target) {
        for (int i = left; i <= right; i++) {
            if (inorder[i] == target) {
                return i;
            }
        }
        return -1;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

105.从前序与中序遍历构造二叉树

LeetCode连接 105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

题目描述

方法1:递归

前序数组的第一个元素就是中序数组的分割点(根节点)

package daimasuixiangshuati.day18_erchashu;

/**
 * @Author LeiGe
 * @Date 2023/11/20
 * @Description todo
 */
public class CongQianXuYuZhongXuBianLiXuLieGouZaoErChaShu105_1 {
    /**
     * 方法1:dfs-递归
     * 1.先从中序数组只的第一个位置找到根节点
     * 2.创建根节点
     * 3.再在中序数组中找到根节点索引,根据跟节点划分左子树区间,右子树区间
     * 4.根据步骤3,划分前序数组的左子树区间,右子树区间
     * 5.递归得到左右子树
     * 注意:所有区间都是:左闭右闭
     *
     * @param preorder
     * @param inorder
     * @return
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return dfs(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private TreeNode dfs(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
        //baseCase
        if (inRight - inLeft < 0) {
            return null;
        }
        if (inRight - inLeft == 0) {
            return new TreeNode(inorder[inLeft]);
        }

        //前序数组的第一个就是中序数组中的分割点(根节点)
        int rootVal = preorder[preLeft];
        TreeNode root = new TreeNode(rootVal);
        //在中序数组中寻找根节点所在位置的索引,用来分割
        int rootIndex = findMidIndex(inorder, inLeft, inRight, rootVal);
        //根据rootIndex划分左右子树
        //中序数组:
        //左子树区间:[inLeft,rootIndex-1] 右子树区间:[rootIndex+1,inRight]
        //前序数组:
        //左子树区间:[preLeft+1,preLeft+(rootIndex-inLeft)]  右子树区间:[preLeft+(rootIndex-inLeft)+1,preRight]

        //获取左子树
        TreeNode leftNode = dfs(preorder, preLeft + 1, preLeft + (rootIndex - inLeft), inorder, inLeft, rootIndex - 1);
        TreeNode rightNode = dfs(preorder, preLeft + (rootIndex - inLeft) + 1, preRight, inorder, rootIndex + 1, inRight);
        root.left = leftNode;
        root.right = rightNode;
        return root;
    }

    /**
     * 在中序数组中找到根节点所在的索引
     *
     * @param inorder
     * @param left
     * @param right
     * @param target
     * @return
     */
    private int findMidIndex(int[] inorder, int left, int right, int target) {
        for (int i = left; i <= right; i++) {
            if (inorder[i] == target) {
                return i;
            }
        }
        return -1;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

小结

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值