树的专题
Preorder | Inorder | Postorder | Levelorder | |
---|---|---|---|---|
Recursion | DFS | DFS | DFS | DFS |
Iteration | Stack | Stack | Stack | Queue |
四种遍历模板
Preorder | Inorder | Postorder | Levelorder | |
---|---|---|---|---|
Recursion | DFS | DFS | DFS | Queue |
特点 | Stack | BST | 子模块 | Queue |
257.Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//Preorder
//空间复杂度为O(h)
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if(root == null) return res;
helper(res, root, "");
return res;
}
public void helper(List<String> res, TreeNode root, String path) {
if (root.left == null && root.right == null) {
res.add(path + root.val);
}
if (root.left != null) {
//path一开始是”“,后来加入了"x->","y->""
helper(res, root.left, path + root.val + "->");
}
if (root.right != null) {
helper(res, root.right, path + root.val + "->");
}
}
}
113.Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//PreOrder
//从上到下遍历,到最后一层截止即可。
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
helper(res, new ArrayList<>(), root, sum);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list ,TreeNode root, int sum) {
if (root == null) return;
list.add(root.val);
if (root.left == null && root.right == null) {
if (sum == root.val) {
res.add(new ArrayList<>(list));
}
}
helper(res, list, root.left, sum - root.val);
helper(res, list, root.right, sum - root.val);
list.remove(list.size() - 1);//删掉叶子节点,如果没有的话,List就会无限向后加,back trackiing
//然后在helper()执行完毕以后,向上遍历,并返回list.remove(),也就是看父节点的另外一个叶子节点
}
}
双PRE
298. Binary Tree Longest Consecutive Sequence(Preorder)(付费题)
找出二叉树中连续的最长序列(不能忽然从子树换到BST的另外一颗子树)
- 要求返回值为连续最长序列的父节点
//当前节点的值是前一个节点的值 + 1
//max:当前整体长度,最后去和res比较
//target:判断下一个数是否等于target
//max = 1走到这里的时候断了
private int res = 0;
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
helper(root, 0, root.val);
return res;
}
public void helper(TreeNode root, int max, int target) {
if (root == null) return;
if (root.val == target) {
max++;
} else max = 1;
res = Math.max(res, max);
helper(root.left, max, root.val + 1);
helper(root.right, max, root.val + 1);
}
100.Same Tree
Share
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:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
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
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//双PRE
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return helper(root.left, root.right);
}
public boolean helper(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
//反过来,就变成100题了
return helper(p.left, q.right) && helper(p.right, q.left);
}
}
112. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if(root.left == null && root.right == null) {
return root.val == sum;
}
//判断sum从root一直减下去的值是否等于那条路径的最终的叶子节点
//从上到下遍历,到最后一层截止即可。
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
129. Sum Root to Leaf Numbers
Share
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
public int helper(TreeNode root, int num) {
if (root == null) return 0;
if (root.left == null && root.right == null) {
return num * 10 + root.val;
}
return helper(root.left, num * 10 + root.val) +
helper(root.right, num * 10 + root.val);
}
}
111.Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null || root.right == null) {
//case:只有一个子树
return Math.max(minDepth(root.left), minDepth(root.right)) + 1;//+1是因为层数是从下到上数到,最下层的起始层数应该为0
}
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
98.Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
return helper(root, null, null);
}
public static boolean helper(TreeNode root, Integer min, Integer max) {
if (root == null) return true;
if (min != null && root.val <= min) return false;
if (max != null && root.val >= max) return false;
return helper(root.left, min, root.val) && helper(root.right, root.val, max);
}
}
513. Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
int height = 0;//记录当前的高度
public int findBottomLeftValue(TreeNode root) {
if (root == null) return -1;
helper(root ,1);//1就是depth
return res;
}
public void helper(TreeNode root, int depth) {
if (root == null) return;
if (height < depth) {//没找到最下面就继续找
res = root.val;
height = depth;
}
helper(root.left, depth + 1);
helper(root.right, depth +1);
}
}