😊
Populating Next Right Pointers in Each Node
September 04, 2022
문제 링크
조건
- 트리가 가지고 있는 node 갯수 [0, 2^12 - 1].
- -1000 <= Node.val <= 1000
입력값
- root = perfect Binary Tree의 루트
- node의 구조
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
- next pointe는 모두 NULL로 초기화 되어 있음
출력값
- root = perfect Binary Tree의 루트
풀이과정
- tree를 traverse 하면서
- root가 null이거나 root.left 요소가 없는 경우 return
- root 에서 오른쪽에 node가 있으면 root.left.next에 해당 node를 넣어준다
- 현재 root 에 next가 있으면 root.right.next에 next의 왼쪽에 있는 node를 넣어주고 next가 없으면 null을 넣어준다
코드
var connect = function (root) {
if (!root || !root.left) return root;
root.left.next = root.right;
root.right.next = root.next ? root.next.left : null;
connect(root.left);
connect(root.right);
return root;
};
😊