Leetcode - 814. Binary Tree Pruning

숲사람·2022년 9월 6일
0

멘타트 훈련

목록 보기
139/237

문제

0과1로 이루어진 이진트리에서 자식트리에 1이 없는 노드를 삭제해라.

https://leetcode.com/discuss/general-discussion/1152824/cracking-the-coding-interview-6th-edition-in-leetcode

해결

0 ms, faster than 100.00% of C
leaf노드가 0일때 NULL을 리턴 -> 이걸 재귀적으로(후위 순회) 반복. 처음에 pre order 순으로 체크했다가 에러발생, post order로 해야함.

struct TreeNode* pruneTree(struct TreeNode* root){
    if (root == NULL)
        return NULL;
    
    root->left = pruneTree(root->left);
    root->right = pruneTree(root->right);
    if (root && root->val == 0 && !root->left && !root->right)
        return NULL;
    return root;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글