java 求二叉树的深度

来源:互联网 发布:cf手雷威力排行 数据 编辑:程序博客网 时间:2024/05/21 12:44

题目:

输入一个二叉树的根节点,求该数的深度。

此题比较简单,主要考察递归思想,算法实现如下:

/**public 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;        if(root.left==null&&root.right==null)            return 1;        if(root.left==null)            return TreeDepth(root.right)+1;        if(root.right==null)            return TreeDepth(root.left)+1;        return max(TreeDepth(root.left),TreeDepth(root.right))+1;    }    public int max(int a,int b){        return a>b?a:b;    }}
1 0