牛客网编程-二叉树的深度(java)

来源:互联网 发布:校花级别的多漂亮知乎 编辑:程序博客网 时间:2024/06/08 05:23

思路:求二叉树的深度,想到左右子树递归


代码:

/**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;        }        int deepth = 1;        int left = this.TreeDepth(root.left);        int right = this.TreeDepth(root.right);deepth += left > right?left:right;        return deepth;    }}
end

原创粉丝点击