二叉树的深度
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如: 给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
int num =1;
while(!queue.isEmpty()){
LinkedList<TreeNode> list = new LinkedList<>();
while(!queue.isEmpty()){
TreeNode node = queue.pop();
if(node.left != null){
list.add(node.left);
}
if(node.right != null){
list.add(node.right);
}
}
if(!list.isEmpty()){
num++;
queue.addAll(list);
}
}
return num;
}
}
平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true
。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false
。
限制:
0 <= 树的结点个数 <= 10000
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs(getHigh(root.left)-getHigh(root.right))<=1){
return isBalanced(root.left)&&isBalanced(root.right);
}
return false;
}
private int getHigh(TreeNode root){
if(root==null) return 0;
return Math.max(getHigh(root.left),getHigh(root.right))+1;
}
}
二叉搜索树的最近公共祖先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode res;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
postOrder(root, p, q);
return res;
}
private int postOrder(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return 0;
}
int lcnt = postOrder(root.left, p, q);
int rcnt = postOrder(root.right, p, q);
if(lcnt ==1 && rcnt ==1){
res = root;
} else if(lcnt ==1 || rcnt ==1) {
if(root ==p || root==q){
res = root;
}
}
return lcnt + rcnt + ((root==p||root==q)? 1:0);
}
}