본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_09 - Maximum Width of Binary Tree

by HaningYa 2020. 7. 9.
728x90

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com


문제

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:

Input: 

           1
         /   \
        3     2
       / \     \  
      5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input: 

          1
         /  
        3    
       / \       
      5   3     

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input: 

          1
         / \
        3   2 
       /        
      5      

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

Input: 

          1
         / \
        3   2
       /     \  
      5       9 
     /         \
    6           7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

Note: Answer will in the range of 32-bit signed integer.


BST를 기본으로 뼈대를 잡는다.

문제에서 특이한 점은 중간 node 가 nil 이라도 width 는 nil을 포함한 제일 왼쪽 노드 부터 제일 오른쪽 노드까지 포함해서 계산한다.

그러기 위해서 BST 에서 사용되는 queue에 본인 node의 수평적 위치를 저장하는 Int를 추가한다.

그리고 maxWidth 를 수평상의 (queue 내의) 첫번째 노드와 마지막 노드의 거리로 구한다.

아직 잘 모르겠따.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init() { self.val = 0; self.left = nil; self.right = nil; }
 *     public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
 *     public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
 *         self.val = val
 *         self.left = left
 *         self.right = right
 *     }
 * }
 */
class Solution {
    func widthOfBinaryTree(_ root: TreeNode?) -> Int {
        guard let root = root else{
            return 0
        }
        
        var maxWidth = 1
        var queue : [(TreeNode,Int)] = []
        
        queue.append((root,0))
        
        while(!queue.isEmpty){
            var count = queue.count
            let firstNode = queue.first!
            let lastNode = queue.last!
            
            maxWidth = max(maxWidth,lastNode.1 - firstNode.1 + 1)
            
            while(count > 0){
                var (node,val) = queue.removeFirst()
                if let leftNode = node.left {
                    queue.append((leftNode,val*2-1))
                }
                if let rightNode = node.right {
                    queue.append((rightNode,val*2))
                }
                count -= 1
            }
            
        }
        
        return maxWidth
    }
}

 

 

 

Swift - BFS iteration on Binary Tree

[1,3,2,5,3,null,9] func bfs(_ root: TreeNode?) -> Int { if root == nil { return 0 } var maxWidth = 0 var queue : [TreeNode] = [] queue.append(root!) while(!queue.isEmpty){ var count = queue.count m..

haningya.tistory.com

 

728x90

댓글