网站建设网络推广代理公司/北京百度搜索优化
二叉树高度相关的算法题,主要是用递归算法来求解。
关于树的高度,主要有以下几种题目。

在线oj地址:
1.二叉树的最大深度-leetcode104
2.二叉树的最小深度 -leetcode111
1.二叉树的最大深度
思路:
遍历二叉树,二叉树的高度为左右子树中,高度更大的那个。
递归遍历代码:
class Solution {public int maxDepth(TreeNode root) {if(root==null){return 0;}return Math.max(maxDepth(root.left),maxDepth(root.right))+1;}
}
2.二叉树的最小深度
题目描述:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
解题思路:
访问某一节点,
若左右孩子均不为空,则最小深度为较小的子树的深度+1。
若有一个孩子节点不为空,则最小深度为该非空节点子树的深度+1。
若两个孩子节点均为空,则最小深度为1
实现代码如下:
class Solution {public int minDepth(TreeNode root) {if(root == null){return 0;}if(root.left != null && root.right !=null){return Math.min(minDepth(root.left),minDepth(root.right))+1;}return root.left!=null? minDepth(root.left)+1:minDepth(root.right)+1; }
}