본문 바로가기
Algorithm/Study

이진트리 연산

by HaningYa 2021. 1. 16.
728x90
 

Maximum Depth of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

  • node count
  • leaf node
  • node height
/**
 * 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 maxDepth(_ root: TreeNode?) -> Int {
        print("node count \(countNode(root))")
        print("node height \(returnHeight(root))")
        print("node leaf count \(leafNode(root))")
        return returnHeight(root)
    }
    func returnHeight(_ node: TreeNode?) -> Int {
        var height = 0
        if let node = node {
            height = 1 + max(returnHeight(node.left), returnHeight(node.right))
        }
        return height
    }
    func countNode(_ node: TreeNode?) -> Int {
        var count = 0
        if let node = node {
            count = 1 + countNode(node.left) + countNode(node.right)
        }
        return count
    }
    func leafNode(_ node: TreeNode?) -> Int {
        var count = 0
        if let node = node {
            if node.left == nil && node.right == nil {
                return 1
            }else{
                count = leafNode(node.left) + leafNode(node.right)
            }
        }
        return count
    }
}
728x90

'Algorithm > Study' 카테고리의 다른 글

Graph Swift (BFS, DFS)  (0) 2021.01.20
Swift Heap  (0) 2021.01.18
이진트리 순회  (0) 2021.01.16
Swift Sorting Algorithm Note  (0) 2021.01.13
Swift 다항식 덧셈  (0) 2020.09.11

댓글