IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 数据结构与算法 -> LeetCode常见题型——树 -> 正文阅读

[数据结构与算法]LeetCode常见题型——树

1. 算法思想

作为(单)链表的升级版,我们通常接触的树都是二叉树(binary tree),即每个节点最多有
两个子节点;且除非题目说明,默认树中不存在循环结构。

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

2.常见题型

2.1 树的递归

对于一些简单的递归题,某些LeetCode 达人喜欢写one-line code,即用一行代码解决问题,
把if-else 判断语句压缩成问号冒号的形式。

LeetCode-104. Maximum Depth of Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, return its maximum depth.https://blog.csdn.net/qq_15711195/article/details/122390238LeetCode-110. Balanced Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given a binary tree, determine if it is height-balanced.https://blog.csdn.net/qq_15711195/article/details/122288238LeetCode-543. Diameter of Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, returnthe length of thediameterof the tree. Thediameterof a binary tree is thelengthof the longest path between any two nodes in a tree. This path may or may not pass through theroot.https://blog.csdn.net/qq_15711195/article/details/122392821LeetCode-112. Path Sum [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree and an integertargetSum, returntrueif the tree has aroot-to-leafpath such that adding up all the values along the path equalstargetSum. Aleafis a node with no children.https://blog.csdn.net/qq_15711195/article/details/126316873LeetCode-113. Path Sum II [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree and an integertargetSum, returnallroot-to-leafpaths where the sum of the node values in the path equalstargetSum. Each path should be returned as a list of the nodevalues, not node references.https://blog.csdn.net/qq_15711195/article/details/126317281LeetCode-437. Path Sum III [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree and an integertargetSum, returnthe number of paths where the sum of the valuesalong the path equalstargetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only ...https://blog.csdn.net/qq_15711195/article/details/126239920LeetCode-101. Symmetric Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree,check whether it is a mirror of itself(i.e., symmetric around its center).https://blog.csdn.net/qq_15711195/article/details/126317542LeetCode-572. Subtree of Another Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given the roots of two binary treesrootandsubRoot, returntrueif there is a subtree ofrootwith the same structure and node values ofsubRootandfalseotherwise. A subtree of a binary treetreeis a tree that consists of a node intreeand all of th...https://blog.csdn.net/qq_15711195/article/details/126331459LeetCode-1110. Delete Nodes And Return Forest [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, each node in the tree has a distinct value.After deleting all nodes with a value into_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest.https://blog.csdn.net/qq_15711195/article/details/126320648

LeetCode-226. Invert Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, invert the tree, and returnits root.https://blog.csdn.net/qq_15711195/article/details/126329758?spm=1001.2014.3001.5502LeetCode-617. Merge Two Binary Trees [C++][Java]_贫道绝缘子的博客-CSDN博客Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as thttps://blog.csdn.net/qq_15711195/article/details/126329917?spm=1001.2014.3001.5502LeetCode-404. Sum of Left Leaves [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, returnthe sum of all left leaves. Aleafis a node with no children. Aleft leafis a leaf that is the left child of another node.https://blog.csdn.net/qq_15711195/article/details/126331670?spm=1001.2014.3001.5502

2.2 层次遍历

可以使用广度优先搜索进行层次遍历。

注意,不需要使用两个队列来分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。

LeetCode-637. Average of Levels in Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, returnthe average value of the nodes on each level in the form of an array. Answers within10-5of the actual answer will be accepted.https://blog.csdn.net/qq_15711195/article/details/126321340

LeetCode-513. Find Bottom Left Tree Value [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, return the leftmost value in the last row of the tree.https://blog.csdn.net/qq_15711195/article/details/126331850?spm=1001.2014.3001.5502

2.3 前中后序遍历

前序遍历先遍历父结点,再遍历左结点,最后遍历右节点

void preorder(TreeNode* root) {
    visit(root);
    preorder(root->left);
    preorder(root->right);
}

中序遍历先遍历左节点,再遍历父结点,最后遍历右节点

void inorder(TreeNode* root) {
    inorder(root->left);
    visit(root);
    inorder(root->right);
}

后序遍历先遍历左节点,再遍历右结点,最后遍历父节点

void postorder(TreeNode* root) {
    postorder(root->left);
    postorder(root->right);
    visit(root);
}

?已知二叉树,求三种序列

LeetCode-144. Binary Tree Preorder Traversal [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, returnthe preorder traversal of its nodes' values.https://blog.csdn.net/qq_15711195/article/details/126322090?spm=1001.2014.3001.5502LeetCode-94. Binary Tree Inorder Traversal [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary tree, returnthe inorder traversal of its nodes' values.https://blog.csdn.net/qq_15711195/article/details/126339414?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22126339414%22%2C%22source%22%3A%22qq_15711195%22%7DLeetCode-145. Binary Tree Postorder Traversal [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof abinary tree, returnthe postorder traversal of its nodes' values.https://blog.csdn.net/qq_15711195/article/details/126339439

已知两种序列,重建二叉树

LeetCode-105. Construct Binary Tree from Preorder and Inorder Traversal [C++][Java]_贫道绝缘子的博客-CSDN博客Given two integer arrayspreorderandinorderwherepreorderis the preorder traversal of a binary tree andinorderis the inorder traversal of the same tree, construct and returnthe binary tree.https://blog.csdn.net/qq_15711195/article/details/122906206?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22122906206%22%2C%22source%22%3A%22qq_15711195%22%7DLeetCode-106. Construct Binary Tree from Inorder and Postorder Traversal [C++][Java]_贫道绝缘子的博客-CSDN博客Given two integer arraysinorderandpostorderwhereinorderis the inorder traversal of a binary tree andpostorderis the postorder traversal of the same tree, construct and returnthe binary tree.https://blog.csdn.net/qq_15711195/article/details/126339392LeetCode-889. Construct Binary Tree from Preorder and Postorder Traversal [C++][Java]_贫道绝缘子的博客-CSDN博客Given two integer arrays,preorderandpostorderwherepreorderis the preorder traversal of a binary tree ofdistinctvalues andpostorderis the postorder traversal of the same tree, reconstruct and returnthe binary tree.https://blog.csdn.net/qq_15711195/article/details/126334214

利用三序递归

LeetCode-538. Convert BST to Greater Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.https://blog.csdn.net/qq_15711195/article/details/126332103?spm=1001.2014.3001.5502LeetCode-235. Lowest Common Ancestor of a Binary Search Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.https://blog.csdn.net/qq_15711195/article/details/122254051LeetCode-236. Lowest Common Ancestor of a Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.https://blog.csdn.net/qq_15711195/article/details/122254830LeetCode-530. Minimum Absolute Difference in BST [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a Binary Search Tree (BST), returnthe minimum absolute difference between the values of any two different nodes in the tree.https://blog.csdn.net/qq_15711195/article/details/126332933?spm=1001.2014.3001.5502LeetCode-897. Increasing Order Search Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary search tree, rearrange the tree inin-orderso that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.https://blog.csdn.net/qq_15711195/article/details/126339535?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22126339535%22%2C%22source%22%3A%22qq_15711195%22%7DLeetCode-653. Two Sum IV - Input is a BST [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a Binary Search Tree and a target numberk, returntrueif there exist two elements in the BST such that their sum is equal to the given target.https://blog.csdn.net/qq_15711195/article/details/126339582?spm=1001.2014.3001.5502

2.4?二叉查找树

二叉查找树(Binary Search Tree, BST)是一种特殊的二叉树:对于每个父节点,其左子节点
的值小于等于父结点的值,其右子节点的值大于等于父结点的值。因此对于一个二叉查找树,我
们可以在O(nlogn)?的时间内查找一个值是否存在:从根节点开始,若当前节点的值大于查找值
则向左下走,若当前节点的值小于查找值则向右下走。同时因为二叉查找树是有序的,对其中序
遍历的结果即为排好序的数组。

template <class T>
class BST {
    struct Node {
        T data;
        Node* left;
        Node* right;
    };
    Node* root;
    
    Node* makeEmpty(Node* t) {
        if (t == NULL) return NULL;
        makeEmpty(t->left);
        makeEmpty(t->right);
        delete t;
        return NULL;
    }
    
    Node* insert(Node* t, T x) {
        if (t == NULL) {
            t = new Node;
            t->data = x;
            t->left = t->right = NULL;
        } else if (x < t->data) {
            t->left = insert(t->left, x);
        } else if (x > t->data) {
            t->right = insert(t->right, x);
        }
        return t;
    }
    
    Node* find(Node* t, T x) {
        if (t == NULL) return NULL;
        if (x < t->data) return find(t->left, x);
        if (x > t->data) return find(t->right, x);
        return t;
    }
    
    Node* findMin(Node* t) {
        if (t == NULL || t->left == NULL) return t;
            return findMin(t->left);
        }
        Node* findMax(Node* t) {
        if (t == NULL || t->right == NULL) return t;
        return findMax(t->right);
    }
    
    Node* remove(Node* t, T x) {
        Node* temp;
        if (t == NULL) return NULL;
        else if (x < t->data) t->left = remove(t->left, x);
        else if (x > t->data) t->right = remove(t->right, x);
        else if (t->left && t->right) {
            temp = findMin(t->right);
            t->data = temp->data;
            t->right = remove(t->right, t->data);
        } else {
            temp = t;
            if (t->left == NULL) t = t->right;
            else if (t->right == NULL) t = t->left;
            delete temp;
        }
        return t;
    }

public:
    BST(): root(NULL) {}
    ~BST() {
        root = makeEmpty(root);
    }
    void insert(T x) {
        insert(root, x);
    }
    void remove(T x) {
        remove(root, x);
    }
};

LeetCode-99. Recover Binary Search Tree [C++][Java]_贫道绝缘子的博客-CSDN博客You are given therootof a binary search tree (BST), where the values ofexactlytwo nodes of the tree were swapped by mistake.Recover the tree without changing its structure.https://blog.csdn.net/qq_15711195/article/details/126328221LeetCode-669. Trim a Binary Search Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary search tree and the lowest and highest boundaries aslowandhigh, trim the tree so that all its elements lies in[low, high]. Trimming the tree shouldnotchange the relative structure of the elementshttps://blog.csdn.net/qq_15711195/article/details/126328363LeetCode-109. Convert Sorted List to Binary Search Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given theheadof a singly linked list where elements aresorted in ascending order, convert it to a height balanced BST.https://blog.csdn.net/qq_15711195/article/details/126339447?spm=1001.2014.3001.5502LeetCode-897. Increasing Order Search Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a binary search tree, rearrange the tree inin-orderso that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.https://blog.csdn.net/qq_15711195/article/details/126339535?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22126339535%22%2C%22source%22%3A%22qq_15711195%22%7DLeetCode-653. Two Sum IV - Input is a BST [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof a Binary Search Tree and a target numberk, returntrueif there exist two elements in the BST such that their sum is equal to the given target.https://blog.csdn.net/qq_15711195/article/details/126339582?spm=1001.2014.3001.5502LeetCode-450. Delete Node in a BST [C++][Java]_贫道绝缘子的博客-CSDN博客Given a root node reference of a BST and a key, delete the node with the given key in the BST. Returntheroot node reference(possibly updated) of the BST.https://blog.csdn.net/qq_15711195/article/details/126339656?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22126339656%22%2C%22source%22%3A%22qq_15711195%22%7D

2.5 字典树

字典树(Trie)用于判断字符串是否存在或者是否具有某种字符串前缀。

可以在O(n)——近似O(1)的时间内完成搜索,且额外开销非常小。

LeetCode-208. Implement Trie (Prefix Tree) [C++][Java]_贫道绝缘子的博客-CSDN博客?Atrie(pronounced as "try") orprefix treeis a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.https://blog.csdn.net/qq_15711195/article/details/126328615

  数据结构与算法 最新文章
【力扣106】 从中序与后续遍历序列构造二叉
leetcode 322 零钱兑换
哈希的应用:海量数据处理
动态规划|最短Hamilton路径
华为机试_HJ41 称砝码【中等】【menset】【
【C与数据结构】——寒假提高每日练习Day1
基础算法——堆排序
2023王道数据结构线性表--单链表课后习题部
LeetCode 之 反转链表的一部分
【题解】lintcode必刷50题<有效的括号序列
上一篇文章      下一篇文章      查看所有文章
加:2022-08-19 19:31:09  更:2022-08-19 19:34:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/28 18:23:17-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计