leetcode 513. 找树左下角的值

题目描述

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

假设二叉树中至少有一个节点。

示例

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

题目链接

https://leetcode.cn/problems/find-bottom-left-tree-value/

解题思路

层序遍历,最后一层第一个节点的值即为目标值

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> que = new LinkedList<>();
        if (root != null) que.offer(root);
        int res = 0;
        while (!que.isEmpty()) {
            res = que.peek().val;
            int len = que.size();
            while (len-- > 0) {
                TreeNode node = que.poll();
                if (node.left != null) que.offer(node.left);
                if (node.right != null) que.offer(node.right);
            }
        }
        return res;
    }
}

leetcode 112. 路径总和

题目描述

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

叶子节点 是指没有子节点的节点。

示例

输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。

题目链接

https://leetcode.cn/problems/path-sum/

解题思路

递归查找,如果当前节点是叶子节点,则判断当前的 target==root.val,其余情况,只需左子树和右子树有一种满足即可

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

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

题目描述

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

示例

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

题目链接

https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal

解题思路

根据中序遍历和后续遍历的定理,以后续遍历的下标为准(根节点最后输出),将中序遍历切割左右两个部分,分别对应左右子树。然后再对左右子树递归构造。递归子树的顺序不能变,一定是先构造右子树再构造左子树。因为后序输出是 左 - 右 - 中

class Solution {
    int post_idx; // 后序遍历的访问下标
    int[] postorder;
    int[] inorder;
    Map<Integer, Integer> idx_map = new HashMap<>();
    public TreeNode helper(int left_index, int right_index) {
        // 没有需要构造的二叉树
        if (left_index > right_index) return null;

        int root_val = postorder[post_idx];
        // 构造节点
        TreeNode root = new TreeNode(root_val);

        // 根节点在中序遍历的下标
        int index = idx_map.get(root_val);

        post_idx--;
        // 顺序不能变,后序遍历是 左-右-中
        // 构造右子树
        root.right = helper(index + 1, right_index);
        // 构造左子树
        root.left = helper(left_index, index - 1);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.inorder = inorder;
        this.postorder = postorder;
        post_idx = postorder.length - 1;
        for (int i = 0; i < inorder.length; i++) {
            idx_map.put(inorder[i], i);
        }
        return helper(0, inorder.length - 1);

    }
}