Algorithm
606 : Construct String from Binary Tree ( leetcode / java )
코동이
2020. 10. 29. 11:12
*해결과정
앞에 문제가 이진탐색트리인데 제대로 살펴보지 않았기 때문에 이제 꼭 어떤 트리종류인지를 확인한다!! 아쉽게도 이번에는 아무 트리도 아니다 ㅋㅋ 순회하면서 괄호를 포함시키는 문제이다. 특이한 점은 Example 2에서 왼쪽 괄호가 null 일 때는 ()를 반환해야 한다는 것이다. 간단하게 조건문을 걸어 재귀로 해결한다.
class Solution {
public String tree2str(TreeNode t) {
if(t==null) return "";
String line = t.val+"";
if(t.left!=null) {
line += "(" + tree2str(t.left) + ")";
}
if(t.left==null && t.right!=null) {
line +="()";
}
if(t.right!=null) {
line += "(" + tree2str(t.right) + ")";
}
return line;
}
}
반응형