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

LeetCode-2415. Reverse Odd Levels of Binary Tree [C++][Java]_贫道绝缘子的博客-CSDN博客Given therootof aperfectbinary tree, reverse the node values at eachoddlevel of the tree.https://blog.csdn.net/qq_15711195/article/details/128336550?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22128336550%22%2C%22source%22%3A%22qq_15711195%22%7D

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值