Maximum Depth of Binary Tree

Recursive Call

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

์ž๋ฃŒ๊ตฌ์กฐ : N/A

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ์žฌ๊ท€ํ˜ธ์ถœ์„ ํ†ตํ•ด ์žŽ๋…ธ๋“œ๊นŒ์ง€ ๋‚ด๋ ค๊ฐ„๋‹ค. - Null์„ ๋งŒ๋‚  ๋•Œ๊นŒ์ง€ ์žฌ๊ท€ํ˜ธ์ถœ๋กœ ์ญ‰ ๋‚ด๋ ค๊ฐ„๋‹ค! 2. Null์„ ๋งŒ๋‚˜๋ฉด ๋น„๋กœ์†Œ ๊ฐ’์„ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค! 0 ๋˜๋Š” 1. - left:0, right:0, Math.max(0,0)+1 = 1

์•Œ๊ณ ๋ฆฌ์ฆ˜์„ Java๋กœ

package graph;
import java.util.*;

class TreeNode {
	     int val;
	     TreeNode left;
	     TreeNode right;
	     TreeNode() {}
	     TreeNode(int val) { this.val = val; }
	     TreeNode(int val, TreeNode left, TreeNode right) {
	         this.val = val;
	         this.left = left;
	         this.right = right;
	     }
	 }
public class MaxDepthBT {//recursive call

	public static void main(String[] args) {
		TreeNode root = new TreeNode(3);
		root.left = new TreeNode(1);
		root.right = new TreeNode(4);
		root.left.left = new TreeNode(5);
		root.left.right = new TreeNode(8);
		root.left.left.left = new TreeNode(7);
		
		System.out.println(solve(root));
	}
	
	public static int solve(TreeNode root) {
		if(root == null) return 0;
		
		int left = solve(root.left);
		int right = solve(root.right);
		return Math.max(left, right)+1;
	}

}

Last updated

Was this helpful?