首页 > 试题广场 >

怎么求一个二叉树的深度?手撕代码?

[问答题]
怎么求一个二叉树的深度?手撕代码?
public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return depth(root);
    }

    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        return Math.max(left, right) + 1;
    }
}

发表于 2020-11-20 11:09:23 回复(0)

DFS

发表于 2019-06-17 15:39:06 回复(0)
深度优先遍历
发表于 2019-06-17 09:30:11 回复(0)
深度优先 广度优先 递归
发表于 2019-04-19 19:48:02 回复(0)

1.后序遍历,最长栈长即为树的深度

2.递归,最后比较即可

3.遍历求层,层次即为深度

发表于 2019-03-28 13:03:54 回复(0)