深度是往下走,而高度是往上走
山之高往上看,海之深往下看
都是从一开始数
高度:任意一节点到叶子节点的距离(后序遍历求)
深度:任意一节点到根节点的距离(前序遍历求)
/**
* 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) {
return getHeight(root);
}
//用后序遍历来求最大高度得出最大深度
public int getHeight(TreeNode node){
if(node==null){
return 0;
}
int left = getHeight(node.left);//左
int right= getHeight(node.right);//右
int height=Math.max(left,right)+1;//中,从一开始so要加一
return height;
}
}
注意题目有小坑
/**
* 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) {
return minHeight(root);
}
public int minHeight(TreeNode node){
if(node==null){
return 0;
}
int left=minDepth(node.left);
int right=minDepth(node.right);
//注意题目:最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
// 当一个左子树为空,右不为空,这时并不是最低点
if (node.left == null && node.right != null) {
return 1 + right;
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node.left != null && node.right == null) {
return 1 + left;
}
int height=Math.min(left,right)+1;
return height;
}
}
/**
* 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 countNodes(TreeNode root) {
return numsOfTree(root);
}
//依旧是后序遍历+递归
public int numsOfTree(TreeNode root){
if(root==null){
return 0;
}
int left=numsOfTree(root.left);
int right=numsOfTree(root.right);
int nums=left+right+1;
return nums;
}
}