[leetcode] 606. Construct String from Binary Tree

kldaji·2022년 9월 7일
0

leetcode

목록 보기
49/56

class Solution {

    fun tree2str(root: TreeNode?): String {
        val sb = StringBuilder()
        
        tree2str(root, sb)
        
        return sb.toString()
    }    
    
    fun tree2str(root: TreeNode?, sb: StringBuilder) {
        if (root == null) return
        
        sb.append(root.`val`)
        
        if (root.left == null && root.right == null) return
        
        sb.append("(")
        tree2str(root.left, sb)
        sb.append(")")   
        
        if (root.right != null) {
            sb.append("(")
            tree2str(root.right, sb)     
            sb.append(")")     
        }
    }
}
profile
다양한 관점에서 다양한 방법으로 문제 해결을 지향하는 안드로이드 개발자 입니다.

0개의 댓글