一、二叉树深度和高度概念
一般书籍都是表示:二叉树的最大层数,高度即:从叶子节点往根节点数,深度则相反.
如图:二叉树的深度和高度都为3
二、求一棵二叉树的深度
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
//求二叉树的深度
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null)return 0;
return Math.max(TreeDepth(root.left)+1,TreeDepth(root.right)+1);
}
public static void main(String[]args){
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
root.left.left=new TreeNode(4);
root.left.right=new TreeNode(5);
root.left.left.left=new TreeNode(6);
root.left.left.right=new TreeNode(7);
Solution s=new Solution();
System.out.println(s.TreeDepth(root));
}
}