美文网首页
求二叉树深度

求二叉树深度

作者: 名字是乱打的 | 来源:发表于2022-04-04 21:26 被阅读0次
1.思路

递归查找每路到叶子结点的深度,找出最大的

2.代码

1.回溯
自底向上,每次返回左右子树更大的深度

 public int TreeDepth(TreeNode root) {
       if (root==null){
            return 0;
        }
        int depth=0;
        int leftDepth = TreeDepth(root.left);
        int rightDepth=TreeDepth(root.right);
        return depth=leftDepth>rightDepth?leftDepth+1:rightDepth+1;
    }

2.常见递归解答代码:

public class TreeDepth_38 {
    int depth = 0;

    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        deepSearch(root, 1);
        return depth;
    }

    private void deepSearch(TreeNode root, int i) {
        if (root.left == null && root.right == null && i > depth) {
            depth = i;
            return;
        }
        if (root.left != null) {
            deepSearch(root.left, i + 1);
        }
        if (root.right != null) {
            deepSearch(root.right, i + 1);
        }
    }

    @Test
    public void test() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        System.out.println(TreeDepth(root));
    }

}

相关文章

网友评论

      本文标题:求二叉树深度

      本文链接:https://www.haomeiwen.com/subject/hvrlsrtx.html