LeetCode hot topic HOT 100: Construct a binary tree from the preorder and inorder traversal sequences, expand the binary tree into a linked list, and the maximum path in the binary tree

LeetCode hot topic HOT 100

105. Construct Binary Tree from Preorder and Inorder Traversal Sequences

Question : Given two integer arrays preorder and inorder, where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree,
please construct a binary tree and return its root node.
Example 1: insert image description here
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

package ricky.com.Hot100;

import java.util.HashMap; 

/**
 * @Author xdg
 */
public class buildTree {
    
    
    /*105. 从前序与中序遍历序列构造二叉树
    给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,
    请构造二叉树并返回其根节点。*/

    // 定义二叉树节点的结构
    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;
        }
    }

    class Solution {
    
    
        // 声明一个 HashMap,用于存储中序遍历数组中每个元素的索引
        HashMap<Integer, Integer> map = new HashMap<>();

        // 构建二叉树的函数,参数为先序遍历数组和中序遍历数组
        public TreeNode buildTree(int[] preorder, int[] inorder) {
    
    
            // 将中序遍历数组中每个元素的值和索引存储到 HashMap 中
            for (int i = 0; i < inorder.length; i++) {
    
    
                map.put(inorder[i], i);
            }

            // 调用递归函数构建二叉树,返回根节点
            return f(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
        }

        // 递归函数,参数为先序遍历数组、中序遍历数组、以及它们在当前递归层次下的边界
        private TreeNode f(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
    
    
            // 如果左边界大于右边界,说明当前子树为空,返回 null
            if (l1 > r1) {
    
    
                return null;
            }

            // 构建当前子树的根节点
            TreeNode root = new TreeNode(preorder[l1]);
            // 在中序遍历数组中找到根节点的位置
            int i = map.get(preorder[l1]);
            // 递归构建左子树,左子树的元素范围为 preorder[l1+1, l1+i-l2] 和 inorder[l2, i-1]
            root.left = f(preorder, l1 + 1, l1 + i - l2, inorder, l2, i - 1);
            // 递归构建右子树,右子树的元素范围为 preorder[l1+i-l2+1, r1] 和 inorder[i+1, r2]
            root.right = f(preorder, l1 + i - l2 + 1, r1, inorder, i + 1, r2);
            // 返回当前子树的根节点
            return root;
        }
    }
}

114. Expand Binary Tree to Linked List

Topic : Given the root node root of your binary tree, please expand it into a singly linked list: the
expanded singly linked list should also use TreeNode, where the right sub-pointer points to the next node in the linked list, and the left sub-pointer is always null .
The expanded singly linked list should be in the same order as the binary tree preorder traversal.
**Example 1:insert image description here

Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]

Idea analysis: First, perform preorder traversal on the binary tree, and store the traversal results in the List. Then traverse the nodes in the List to build a linked list. Specifically, take the first node of the List as the new root node, and set its left pointer to null. Then define a pointer cur, which initially points to the new root node, traverses the remaining nodes in the List, points the right pointer of the current node to the next node, sets the left pointer to null, and then points the pointer cur to the current node, repeating the above process , until all nodes are traversed. Just return at last.

class Solution {
    
    
    List<TreeNode> list = new ArrayList<>(); // 声明一个 List,用于存储先序遍历的结果

    // 将二叉树拉平为链表的函数,参数为二叉树的根节点
    public void flatten(TreeNode root) {
    
    
        if (root == null) {
    
     // 如果根节点为空,直接返回
            return;
        }

        preOrder(root); // 对二叉树进行先序遍历,将结果存储到 List 中
        TreeNode newRoot = list.get(0); // 获取二叉树拉平后的新根节点
        newRoot.left = null; // 将新根节点的左指针置为 null
        TreeNode cur = newRoot; // 定义一个指针,指向当前处理的节点
        for (int i = 1; i < list.size(); i++) {
    
     // 遍历 List 中的节点,构建链表
            cur.right = list.get(i); // 当前节点的右指针指向下一个节点
            cur.left = null; // 当前节点的左指针置为 null
            cur = cur.right; // 将指针指向下一个节点
        }

        return;

    }

    // 递归函数,对二叉树进行先序遍历,并将结果存储到 List 中
    private void preOrder(TreeNode root) {
    
    
        if (root == null) {
    
     // 如果当前节点为空,直接返回
            return;
        }

        list.add(root); // 将当前节点加入到 List 中
        preOrder(root.left); // 递归遍历左子树
        preOrder(root.right); // 递归遍历右子树
    }
}

124. Maximum Path Sum in Binary Tree

Title : A path is defined as a sequence starting from any node in the tree, following the parent-child connection, and reaching any node. The same node
appears at most once in a path sequence. The path contains at least one node and does not necessarily go through the root node.
The path sum is the sum of the values ​​of each node in the path.
Given the root node root of a binary tree, return its maximum path sum. .
**Example 1:insert image description here

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7, and the path sum is 15 + 20 + 7 = 42

Idea analysis: Use post-order traversal to traverse the binary tree, and calculate the maximum path sum with each node as the starting point of the path. For each node, first recursively traverse its left and right subtrees, and calculate the maximum path sum of the left and right subtrees. Then, with the current node as the starting point of the path, calculate the maximum path sum of the current node, that is, calculate the value of the current node plus the sum of the maximum path sum of the left subtree and the maximum path sum of the right subtree, and the value of the current node and the left and right The maximum value in the sum of the maximum paths and sums of subtrees. Finally, update the global maximum path sum to the maximum value of the current path, that is, Math.max(res, Math.max(temp, root.val + left + right)). Finally, return the global maximum path and res.

class Solution {
    
    
    int res = Integer.MIN_VALUE; // 定义全局变量,用于保存最大路径和

    public int maxPathSum(TreeNode root) {
    
    
        if (root == null) {
    
     // 如果根节点为空,返回0
            return 0;
        }

        postOrder(root); // 对树进行后序遍历,计算最大路径和
        return res; // 返回最大路径和
    }

    // 后序遍历二叉树,并计算以当前节点为起点的最大路径和
    private int postOrder(TreeNode root) {
    
    
        if (root == null) {
    
     // 如果当前节点为空,返回0
            return 0;
        }

        // 分别对左子树和右子树进行后序遍历,并计算左子树和右子树的最大路径和
        int left = postOrder(root.left);
        int right = postOrder(root.right);

        // 计算以当前节点为起点的最大路径和,并更新全局最大路径和
        int temp = Math.max(root.val, root.val + Math.max(left, right)); // 计算以当前节点为起点的路径
        res = Math.max(res, Math.max(temp, root.val + left + right)); // 更新全局最大路径和

        // 返回以当前节点为起点的最大路径和
        return temp;
    }
}

Guess you like

Origin blog.csdn.net/weixin_51405802/article/details/130181001