树的数据结构
作为(单)链表的升级版,我们通常接触的树都是二叉树(binary tree),即每个节点最多有两个子节点;且除非题目说明,默认树中不存在循环结构。LeetCode 默认的树表示方法如下。
1 | struct TreeNode { |
可以看出,其与链表的主要差别就是多了一个子节点的指针。
树的递归
LeetCode NO.104 Maximum Depth of Binary Tree
题目描述
返回二叉树的最大深度。
题解
1 | int maxDepth(TreeNode* root) { |
LeetCode NO.110 Balanced Binary Tree
题目描述
判断二叉树是否平衡。
题解
1 | bool isBalanced(TreeNode* root) { |
LeetCode NO.543 Diameter of Binary Tree
题目描述
寻找二叉树的最长直径。直径的定义是二叉树上任意两节点之间的无向距离。
题解
1 | int diameterOfBinaryTree(TreeNode* root) { |
LeetCode NO.437 Path Sum III
题目描述
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10 / \ 5 -3 / \ \ 3 2 11 / \ \
3 -2 1
Return 3. The paths that sum to 8 are:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
题解
1 | class Solution { |
LeetCode NO.101 Symmetric Tree
题目描述
判断一棵二叉树是否对称。
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 1000].
-100 <= Node.val <= 100
题解
判断一个树是否对称等价于判断左右子树是否对称。笔者一般习惯将判断两个子树是否相等或对称类型的题的解法叫做“四步法”:(1)如果两个子树都为空指针,则它们相等或对称;(2)如果两个子树只有一个为空指针,则它们不相等或不对称;(3)如果两个子树根节点的值不相等,则它们不相等或不对称;(4)根据相等或对称要求,进行递归处理。
1 | bool isSymmetric(TreeNode* root) { |
LeetCode NO.1110 Delete Nodes And Return Forest
题目描述
Given the root of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
Example 1:
1 | Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] |
Example 2:
1 | Input: root = [1,2,4,null,3], to_delete = [3] |
Constraints:
The number of nodes in the given tree is at most 1000.
Each node has a distinct value between 1 and 1000.
to_delete.length <= 1000
to_delete contains distinct values between 1 and 1000.
题解
1 | /** |
1 | /** |