代码随想录day16

文章介绍了在给定二叉树的情况下,如何通过迭代和递归的方法找到最底层左节点的值,以及如何判断是否存在根到叶子节点的路径和等于给定目标和。同时提到了从中序遍历和后序遍历数组构建二叉树的方法。

二叉树 5

找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。
在这里插入图片描述

思路

本题利用队列层序打印较简单,保留每一层最先出队的值,即可
递归思路较难,需要考虑的是最底层最左侧的值,因此要找到最底层,才记录值,

迭代

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int left = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0;i < size;i++){
                TreeNode tmp = queue.poll();
                if(i == 0)
                    left = tmp.val;
                if(tmp.left != null)
                    queue.offer(tmp.left);
                if(tmp.right != null)
                    queue.offer(tmp.right);
            }
        }
        return left;
    }
}

递归

class Solution {
    int maxDep = Integer.MIN_VALUE;
    int res = 0;
    public int findBottomLeftValue(TreeNode root) {
        recur(root,0);
        return res;
    }
    public void recur(TreeNode root,int dep){
        if(root.left == null && root.right == null){
            if(dep > maxDep){
                maxDep = dep;
                res = root.val;
            }
            return;
        }

        if(root.left != null)
            recur(root.left,dep + 1);
        if(root.right != null)
            recur(root.right,dep + 1);
            
        
    }
}

路径总和 1

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。

叶子节点 是指没有子节点的节点。
在这里插入图片描述

路径总和 2

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。
在这里插入图片描述

思路

两个思路一样的题目,需要注意的是到叶子节点,以及回溯操作,移除元素。

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null)
            return false;
        if(root.left == null && root.right == null){
            return root.val == targetSum;
        }
        boolean left = false,right = false;
        if(root.left != null)
            left = hasPathSum(root.left,targetSum - root.val);
        if(root.right != null)
            right = hasPathSum(root.right,targetSum - root.val);
        return left || right;
    }
}
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> tmp = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if(root == null)
            return res;
        recur(root,targetSum);
        return res;
    }
    public void recur(TreeNode root,int tar){
        if(root.left == null && root.right == null){
            if(root.val == tar){
                tmp.add(root.val);
                res.add(new ArrayList<>(tmp));
                tmp.remove(tmp.size() - 1);
            }
            return;
        }
        if(root.left != null){
            tmp.add(root.val);
            recur(root.left,tar - root.val);
            tmp.remove(tmp.size() - 1);
        }
            
        if(root.right != null){
            tmp.add(root.val);
            recur(root.right,tar - root.val);
            tmp.remove(tmp.size() - 1);
        }   
    }
}

从中序和后序遍历序列中构造二叉树

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

在这里插入图片描述

思路

通过中序遍历和后序遍历的数组特征,进行递归构造左右子树

在构造的过程中注意边界细节

class Solution {
    // 从中序和后序中找出对应关系
    // 左 根 右 左 右 根

    // 存储中序遍历中根的下标,便于查找
    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
		// 注意参数,长度不 - 1
        TreeNode root = helper(inorder,0,inorder.length ,postorder,0,postorder.length);

        return root;
    }
    public TreeNode helper(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
        if(inEnd <= inBegin || postEnd <= postBegin){
            return null;
        }
        int rootInd = map.get(postorder[postEnd - 1]);
        TreeNode root = new TreeNode(inorder[rootInd]);
        int len = rootInd - inBegin;
        // 确定接下来递归边界
        root.left = helper(inorder,inBegin,rootInd,postorder,postBegin,postBegin + len);
        root.right = helper(inorder,rootInd + 1,inEnd,postorder,postBegin + len,postEnd - 1);
        return root;
    }
}
### 关于代码随想录 Day04 的学习资料与解析 #### 一、Day04 主要内容概述 代码随想录 Day04 的主要内容围绕 **二叉树的遍历** 展开,包括前序、中序和后序三种遍历方式。这些遍历可以通过递归实现,也可以通过栈的方式进行迭代实现[^1]。 #### 二、二叉树的遍历方法详解 ##### 1. 前序遍历(Pre-order Traversal) 前序遍历遵循访问顺序:根节点 -> 左子树 -> 右子树。以下是基于递归的实现: ```python def preorderTraversal(root): result = [] def traversal(node): if not node: return result.append(node.val) # 访问根节点 traversal(node.left) # 遍历左子树 traversal(node.right) # 遍历右子树 traversal(root) return result ``` 对于迭代版本,则可以利用显式的栈来模拟递归过程: ```python def preorderTraversal_iterative(root): stack, result = [], [] current = root while stack or current: while current: result.append(current.val) # 访问当前节点 stack.append(current) # 将当前节点压入栈 current = current.left # 转向左子树 current = stack.pop() # 弹出栈顶元素 current = current.right # 转向右子树 return result ``` ##### 2. 中序遍历(In-order Traversal) 中序遍历遵循访问顺序:左子树 -> 根节点 -> 右子树。递归实现如下: ```python def inorderTraversal(root): result = [] def traversal(node): if not node: return traversal(node.left) # 遍历左子树 result.append(node.val) # 访问根节点 traversal(node.right) # 遍历右子树 traversal(root) return result ``` 迭代版本同样依赖栈结构: ```python def inorderTraversal_iterative(root): stack, result = [], [] current = root while stack or current: while current: stack.append(current) # 当前节点压入栈 current = current.left # 转向左子树 current = stack.pop() # 弹出栈顶元素 result.append(current.val) # 访问当前节点 current = current.right # 转向右子树 return result ``` ##### 3. 后序遍历(Post-order Traversal) 后序遍历遵循访问顺序:左子树 -> 右子树 -> 根节点。递归实现较为直观: ```python def postorderTraversal(root): result = [] def traversal(node): if not node: return traversal(node.left) # 遍历左子树 traversal(node.right) # 遍历右子树 result.append(node.val) # 访问根节点 traversal(root) return result ``` 而迭代版本则稍复杂一些,通常采用双栈法或标记法完成: ```python def postorderTraversal_iterative(root): if not root: return [] stack, result = [root], [] while stack: current = stack.pop() result.insert(0, current.val) # 插入到结果列表头部 if current.left: stack.append(current.left) # 先压左子树 if current.right: stack.append(current.right) # 再压右子树 return result ``` #### 三、补充知识点 除了上述基本的二叉树遍历外,Day04 还可能涉及其他相关内容,例如卡特兰数的应用场景以及组合问题的基础模板[^2][^4]。如果遇到具体题目,可以根据实际需求调用相应算法工具。 --- ####
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值