树
摘录了一些经典的树的题,一共题。
- 树的重建
- 树的遍历(回溯)
- 94. Binary Tree Inorder Traversal (Iteratively) ×
- 144. Binary Tree Preorder Traversal (Iteratively) ×
- 145. Binary Tree Postorder Traversal (Iteratively) ×
- 103. Binary Tree Zigzag Level Order Traversal √
- 102. Binary Tree Level Order Traversal √
- 107. Binary Tree Level Order Traversal II √
- 637. Average of Levels in Binary Tree √
- 515. Find Largest Value in Each Tree Row √
- 513. Find Bottom Left Tree Value √
- 1302. Deepest Leaves Sum √
- 226. Invert Binary Tree √
- 112. Path Sum √
- 111. Minimum Depth of Binary Tree √
- 437. Path Sum III -
- 404. Sum of Left Leaves ×
- 687. Longest Univalue Path ×
- 337. House Robber III √
- 590. N-ary Tree Postorder Traversal √
- 589. N-ary Tree Preorder Traversal √
- 559. Maximum Depth of N-ary Tree √
- 337. House Robber III -
- 树的性质
- 两棵树的判断
树的重建
105. Construct Binary Tree from Preorder and Inorder Traversal -
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
1 | preorder = [3,9,20,15,7] |
Return the following binary tree:
1 | 3 |
1 | public TreeNode buildTree(int[] preorder, int[] inorder) { |
对inorder来说i就是找到的位置,但是对post或者pre来说必须和i-inS有关
106. Construct Binary Tree from Inorder and Postorder Traversal -
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
1 | inorder = [9,3,15,20,7] |
Return the following binary tree:
1 | 3 |
1 | public TreeNode buildTree(int[] inorder, int[] postorder) { |
297. Serialize and Deserialize Binary Tree -
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Example:
1 | You may serialize the following tree: |
递归版本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
buildString(root, sb);
return sb.toString();
}
private void buildString(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append("#,");
} else {
sb.append(node.val+",");
buildString(node.left, sb);
buildString(node.right,sb);
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Deque<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(",")));
return buildTree(nodes);
}
private TreeNode buildTree(Deque<String> nodes) {
String val = nodes.remove();
if (val.equals("#")) return null;
else {
TreeNode node = new TreeNode(Integer.valueOf(val));
node.left = buildTree(nodes);
node.right = buildTree(nodes);
return node;
}
}迭代版本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43public String serialize(TreeNode root) {
if(root==null) return "";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> q = new LinkedList();
q.offer(root);
while(!q.isEmpty()){
TreeNode tmp = q.poll();
if(tmp==null){
sb.append("#,");
continue;
}
sb.append(tmp.val+",");
q.offer(tmp.left);
q.offer(tmp.right);
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.length()==0) return null;
String str[]=data.split(",");
TreeNode root=new TreeNode(Integer.valueOf(str[0]));
Queue<TreeNode> q= new LinkedList();
q.offer(root);
for(int i=1;i<str.length;i++){
TreeNode parent = q.poll();
if(!str[i].equals("#")){
TreeNode left=new TreeNode(Integer.valueOf(str[i]));
parent.left=left;
q.offer(left);
}
if(!str[++i].equals("#")){
TreeNode right=new TreeNode(Integer.valueOf(str[i]));
parent.right=right;
q.offer(right);
}
}
return root;
}
109. Convert Sorted List to Binary Search Tree -
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
1 | Given the sorted linked list: [-10,-3,0,5,9], |
- 暴力法:
1 | public TreeNode sortedListToBST(ListNode head) { |
- 正解
1 | public TreeNode sortedListToBST(ListNode head) { |
99. Recover Binary Search Tree ×
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
1 | Input: [1,3,null,null,2] |
Example 2:
1 | Input: [3,1,4,null,null,2] |
1 | public void recoverTree(TreeNode root) { |
树的遍历(回溯)
94. Binary Tree Inorder Traversal (Iteratively) ×
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
1 | Input: [1,null,2,3] |
1 | public List<Integer> inorderTraversal(TreeNode root) { |
144. Binary Tree Preorder Traversal (Iteratively) ×
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
1 | Input: [1,null,2,3] |
1 | public List<Integer> preorderTraversal(TreeNode root) { |
145. Binary Tree Postorder Traversal (Iteratively) ×
Given a binary tree, return the postorder traversal of its nodes’ values.
Example:
1 | Input: [1,null,2,3] |
1 | public List<Integer> postorderTraversal(TreeNode head) { |
103. Binary Tree Zigzag Level Order Traversal √
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
1 | 3 |
return its zigzag level order traversal as:
1 | [ |
1 | public List<List<Integer>> zigzagLevelOrder(TreeNode root) { |
102. Binary Tree Level Order Traversal √
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
1 | 3 |
return its level order traversal as:
1 | [ |
1 | public List<List<Integer>> levelOrder(TreeNode root) { |
107. Binary Tree Level Order Traversal II √
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
1 | 3 |
return its bottom-up level order traversal as:
1 | [ |
1 | public List<List<Integer>> levelOrderBottom(TreeNode root) { |
637. Average of Levels in Binary Tree √
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
1 | Input: |
1 | public List<Double> averageOfLevels(TreeNode root) { |
515. Find Largest Value in Each Tree Row √
You need to find the largest value in each row of a binary tree.
Example:
1 | Input: |
1 | public List<Integer> largestValues(TreeNode root) { |
513. Find Bottom Left Tree Value √
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
1 | public int findBottomLeftValue(TreeNode root) { |
- 简化版:
1 | public int findBottomLeftValue(TreeNode root) { |
1302. Deepest Leaves Sum √
Given a binary tree, return the sum of values of its deepest leaves.
Example 1:
1 | Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] |
1 | public int deepestLeavesSum(TreeNode root) { |
226. Invert Binary Tree √
Invert a binary tree.
Example:
Input:
1 | 4 |
Output:
1 | 4 |
1 | public TreeNode invertTree(TreeNode root) { |
112. Path Sum √
1 | public boolean hasPathSum(TreeNode root, int sum) { |
111. Minimum Depth of Binary Tree √
1 | public int minDepth(TreeNode root) { |
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:
1 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 |
1 | public int pathSum(TreeNode root, int sum) { |
404. Sum of Left Leaves ×
Find the sum of all left leaves in a given binary tree.
Example:
1 | 3 |
1 | public int sumOfLeftLeaves(TreeNode root) { |
687. Longest Univalue Path ×
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
1 | 5 |
Output: 2
Example 2:
Input:
1 | 1 |
Output: 2
1 | public int longestUnivaluePath(TreeNode root) { |
337. House Robber III √
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
1 | Input: [3,2,3,null,3,null,1] |
Example 2:
1 | Input: [3,4,5,1,3,null,1] |
1 | public int rob(TreeNode root) { |
直接用层次遍历就可以做。
590. N-ary Tree Postorder Traversal √
Given an n-ary tree, return the postorder traversal of its nodes’ values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Follow up:
Recursive solution is trivial, could you do it iteratively?
Example 1:
1 | Input: root = [1,null,3,2,4,null,5,6] |
Example 2:
1 | Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] |
1 | public List<Integer> postorder(Node root) { |
589. N-ary Tree Preorder Traversal √
Given an n-ary tree, return the preorder traversal of its nodes’ values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Follow up:
Recursive solution is trivial, could you do it iteratively?
Example 1:
1 | Input: root = [1,null,3,2,4,null,5,6] |
1 | public List<Integer> preorder(Node root) { |
559. Maximum Depth of N-ary Tree √
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
1 | Input: root = [1,null,3,2,4,null,5,6] |
Example 2:
1 | Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] |
1 | public int maxDepth(Node root) { |
337. House Robber III -
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
1 | Input: [3,2,3,null,3,null,1] |
Example 2:
1 | Input: [3,4,5,1,3,null,1] |
1 | public int rob(TreeNode root) { |
树的性质
897. Increasing Order Search Tree ×
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
1 | Example 1: |
671. Second Minimum Node In a Binary Tree ×
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two
or zero
sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val)
always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
1 | public int findSecondMinimumValue(TreeNode root) { |
98. Validate Binary Search Tree -
中序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14public boolean isValidBST(TreeNode root) {
ArrayList<Integer> rec = new ArrayList();
dfs(root,rec);
for(int i=0;i<rec.size()-1;i++){
if(rec.get(i)>=rec.get(i+1)) return false;
}
return true;
}
public void dfs(TreeNode root,ArrayList<Integer> rec){
if(root==null) return;
dfs(root.left,rec);
rec.add(root.val);
dfs(root.right,rec);
}递归
1
2
3
4
5
6
7
8public boolean isValidBST(TreeNode root) {
return dfs(root,Long.MAX_VALUE,Long.MIN_VALUE);
}
public boolean dfs(TreeNode root,long max,long min){
if(root==null) return true;
if(root.val>=max||root.val<=min) return false;
return dfs(root.left,root.val,min)&&dfs(root.right,max,root.val);
}
110. Balanced Binary Tree √
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
1 | 3 |
Return true.
1 | public boolean isBalanced(TreeNode root) { |
两棵树的判断
101. Symmetric Tree √
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 | 1 |
But the following [1,2,2,null,3,null,3]
is not:
1 | 1 |
1 | public boolean isSymmetric(TreeNode root) { |
100. Same Tree √
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
1 | Input: 1 1 |
Example 2:
1 | Input: 1 1 |
Example 3:
1 | Input: 1 1 |
1 | public boolean isSameTree(TreeNode p, TreeNode q) { |
617. Merge Two Binary Trees √
Given two binary trees and 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 them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
1 | Input: |
1 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { |
572. Subtree of Another Tree √
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
1 | 3 |
Given tree t:
1 | 4 |
1 | public boolean isSubtree(TreeNode s, TreeNode t) { |