LeetCode - Populating Next Right Pointers in Each Node
6691 단어 LeetCode
2014.1.8 05:59
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to
NULL
. Initially, all next pointers are set to
NULL
. Note:
For example,Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
Solution:
It looks like this problem is somewhat related to level-order traversal, but the space limit cannot meet the requirement. You can't use constant space to do a level-order traversal. So we'll do it the preorder way.
Left node is next to the right node, while the right node is next to the leftest node you can find on the same level right to this right node.
Well... I guess the code is better explanation for this problem. I wouldn't waste more words than code to show what I'm doing. Please see the codes below.
Time and space complexities are both O(n), where n is the number of nodes in the tree.
Accepted code:
1 // 1AC, nice
2 /**
3 * Definition for binary tree with next pointer.
4 * struct TreeLinkNode {
5 * int val;
6 * TreeLinkNode *left, *right, *next;
7 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 void connect(TreeLinkNode *root) {
13 // IMPORTANT: Please reset any member data you declared, as
14 // the same Solution instance will be reused for each test case.
15 if(root == nullptr){
16 return;
17 }
18
19 // This algorithm won't work if the tree is not perfect.
20 if(root->left){
21 TreeLinkNode *ll, *rr;
22
23 ll = root->left;
24 rr = root->right;
25 while(ll != nullptr){
26 ll->next = rr;
27 ll = ll->right;
28 rr = rr->left;
29 }
30 }
31 connect(root->left);
32 connect(root->right);
33 }
34 };
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.