本文总结了关于二叉树的相关题目。
先序遍历:
- Divide & Conquer
1 | public List<Integer> preorderTraversal(TreeNode root) { |
- Traverse
1 | public ArrayList<Integer> preorderTraversal(TreeNode root) { |
比较分治法和遍历的区别:
遍历是没有返回值的,使用一个全局变量去记录数据。一个人拿本子去走
而分治法是有返回值的,分左右治之,再把左右值加进去。一个人去布置任务。
Maximum Depth of Binary Tree **
Given a binary 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.
Example
Given a binary tree as follow:
1 | 1 |
- Divide & Conquer
1 | public int maxDepth(TreeNode root) { |
- Traverse
1 | private int max; |
Binary Tree Paths **
Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1 | 1 |
All root-to-leaf paths are:
1 | [ |
- Divide & Conquer
1 | public List<String> binaryTreePaths(TreeNode root) { |
- Traverse
1 | private List<String> result; |
Minimum Subtree **:
Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.
Example
Given a binary tree:
1 | 1 |
1 | private int min = Integer.MAX_VALUE; |
pure d-c
1 | class ResultType { |
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 depth of the two subtrees of every node never differ by more than 1.
Example
Given binary tree A = {3,9,20,#,#,15,7}
, B = {3,#,20,15,7}
1 | A) 3 B) 3 |
The binary tree A is a height-balanced binary tree, but B is not.
1 | private boolean isb; |
Subtree with Maximum Average **
Given a binary tree, find the subtree with maximum average. Return the root of the subtree.
Example :
Given a binary tree:
1 | 1 |
1 | private class resultType{ |
Lowest Common Ancestor **
Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Example
For the following binary tree:
1 | 4 |
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
1 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { |
如果root就是A或者B,那么下面就不用遍历了,因为如果另一个在root的左右子树,那么最低的肯定是root
如果root不是A或者B,那么要考察左右子树,如果左右子树都不空,则root就是最低的。
如果左空右不空,那么右边有A或者B的或者两个都有。
如果右空左不空,那么左边是有A或者B或者两个都有。
如果两个都空,那么这颗树没有A或者B.则返回不了咯。