Trees

Depth of Binary Tree

Estimated reading: 1 minute 42 views

Solution 1

				
					public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
				
			

Solution 2

				
					class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public int maxDepth(TreeNode root) {
        // Base case: if the root is null, the depth is 0
        if (root == null) {
            return 0;
        }

        // Recursively find the depth of the left and right subtrees
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);

        // The depth of the tree is the max of the left and right subtree depths, plus 1
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

				
			

bkz.

preorder traversal

Share this Doc

Depth of Binary Tree

Or copy link

CONTENTS