Algorithm/java tip
Tip3(Easy)
개구리는 개꿀개꿀
2020. 4. 14. 11:49
문제 : https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/submissions/
List<String> bsArray = new ArrayList<>();
public int sumRootToLeaf(TreeNode root) {
StringBuilder sb = new StringBuilder();
sum(root, sb);
int ans = 0;
for(String s : bsArray) {
ans += Integer.parseInt(s, 2);
}
return ans;
}
void sum(TreeNode node, StringBuilder bs) {
if(node != null) {
bs.append(node.val);
if(node.left == null & node.right == null) {
bsArray.add(bs.toString());
}
sum(node.left, bs);
sum(node.right, bs);
if(bs.length() > 0) {
bs.deleteCharAt(bs.length() - 1);
}
}
}
별로 좋은 코드는 아니다
좋은 재귀 연습 문제
https://leetcode.com/problems/maximum-depth-of-binary-tree/
https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/522890/Java-100-2-lines
int max = 0;
public int maxDepth(TreeNode root) {
dfs(root, 0);
return max;
}
public void dfs(TreeNode node, int depth) {
if(node != null) {
depth++;
if(depth > max) max = depth;
dfs(node.left, depth);
dfs(node.right, depth);
}
}
연결된 문제
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
public int maxDepth(Node root) {
if (root == null) return 0;
int max = 0;
for(Node n : root.children) {
int temp = maxDepth(n);
if(temp > max) max = temp;
}
return max + 1;
}