一、二叉树的最大深度(LeetCode104)
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));
}
}
二、n叉树的最大深度(LeetCode559)
递归
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if(root == null){
return 0;
}
int deep = 0;
if(root.children != null){
for(Node tem:root.children){
deep = Math.max(deep,maxDepth(tem));
}
}
return 1 + deep;
}
}
三、二叉树的最小深度(LeetCode111)
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftheight = minDepth(root.left);
int rightheight = minDepth(root.right);
int result = 0;
if(root.left == null && root.right != null){
result = 1 + rightheight;
}else if(root.left != null && root.right == null){
result = 1 + leftheight;
}else{
result = 1 + Math.min(leftheight,rightheight);
}
return result;
}
}
四、完全二叉树的节点个数(LeetCode222)
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
/**
* 针对完全二叉树的解法
*
* 满二叉树的结点数为:2^depth - 1
*/
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
TreeNode left = root.left;
TreeNode right = root.right;
int leftdeep = 0;
int rightdeep = 0;
while(left != null){
left = left.left;
leftdeep++;
}
while(right != null){
right = right.right;
rightdeep++;
}
if(leftdeep == rightdeep){
return (int)Math.pow(2,leftdeep+1)-1;//(2<<leftDepth)-1;注意(2<<1)相当于2^2,所以leftDepth初始为0
}
int leftnum = countNodes(root.left);
int rightnum = countNodes(root.right);
int res = leftnum + rightnum + 1;
return res;
}
}
966

被折叠的 条评论
为什么被折叠?



