leetcode------Populating Next Right Pointers in Each Node II
                                            
 6966 단어  LeetCode
                    
Populating Next Right Pointers in Each Node II
통과율:
31.7%
난이도:
어렵다
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
For example,Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
 , 。  1 /**
 2  * Definition for binary tree with next pointer.
 3  * public class TreeLinkNode {
 4  *     int val;
 5  *     TreeLinkNode left, right, next;
 6  *     TreeLinkNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public void connect(TreeLinkNode root) {
11         int count=1,tmp=0;
12         LinkedList<TreeLinkNode> queue=new LinkedList<TreeLinkNode>();
13         TreeLinkNode start=null,sec=null,pre=null;
14         if(root!=null){
15          queue.addLast(root);
16         }
17         while(!queue.isEmpty()){
18             pre=queue.pollFirst();
19                 if(count==1)pre.next=null;
20                 if(pre.left!=null){
21                     queue.addLast(pre.left);
22                     tmp++;
23                 }
24                 if(pre.right!=null){
25                     queue.addLast(pre.right);
26                     tmp++;
27                 }
28 
29             for(int i=1;i<count;i++){
30                 start=queue.pollFirst();
31                 pre.next=start;
32                 pre=start;
33                 if(start.left!=null){
34                     queue.addLast(start.left);
35                     tmp++;
36                 }
37                 if(start.right!=null){
38                     queue.addLast(start.right);
39                     tmp++;
40                 }
41             }
42             count=tmp;
43             tmp=0;
44             if(start!=null)
45             start.next=null;
46         }
47         
48     }
49 }이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 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에 따라 라이센스가 부여됩니다.