https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

 

Maximum Depth of Binary Tree - LeetCode

Can you solve this real interview question? Maximum Depth of Binary Tree - 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

leetcode.com

 

트리의 깊이를 찾는 문제이다. 트리의 깊이를 찾기 위해 노드를 순차적으로 탐색해야 한다.
탐색하기 위해 Queue를 사용했으며, 노드를 Queue에 삽입할 때 현재의 깊이를 기준으로 1 추가하여 주었고, left 와 right가 null 이 아닌것을 체크하여 Queue에 삽입하고 poll하며 깊이를 확인해 주었다.

 

/**  
 * Definition for a binary tree node. 
 * public 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; 
 *     } 
 * } 
 */  
 
import java.util.*;  
  
public class Solution {  
    public int maxDepth(TreeNode root) {  
        if(root == null) return 0;  
  
        Queue<Depth> que = new ArrayDeque<>();  
        Depth rootDepth = new Depth(root, 1);  
        que.add(rootDepth);  
        int answer = 0;  
  
        while(!que.isEmpty()){  
            Depth curDepth = que.poll();  
            int depth = curDepth.depth;  
            TreeNode cur = curDepth.node;  
            answer = Math.max(depth, answer);  
  
            if(cur.left != null){  
                Depth nextLeftDepth = new Depth(cur.left, depth + 1);  
                que.add(nextLeftDepth);  
            }  
  
            if(cur.right != null){  
                Depth rightLeftDepth = new Depth(cur.right, depth + 1);  
                que.add(rightLeftDepth);  
            }  
        }  
  
        return answer;  
    }  
  
    private class Depth{  
        TreeNode node;  
        int depth;  
  
        Depth(TreeNode node, int depth){  
            this.node = node;  
            this.depth = depth;  
        }  
    }  
}

+ Recent posts