Topic:
Follow up to Problem "populating Next right pointersin each Node".
What if the given tree could is 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 is should look like:
1, NULL / 2, 3, null /\ 4-> 5, 7, NULL
test instructions and analysis:give a tree and link each layer of the tree with the next pointer. Unlike the previous question, this is a random two-fork tree. Here you can use one node to hold the first node of each layer, and then traverse that layer on the line. See the code comment for details. Code:
/*** Definition for binary tree with next pointer. * public class Treelinknode {* Int. val; * Treelinknode left , right, next; * Treelinknode (int x) {val = x;} }*/ Public classSolution { Public voidConnect (Treelinknode root) { while(root!=NULL) {Treelinknode tempchild=NewTreelinknode (0);//record the first node of the next layerTreelinknode Curchild =Tempchild; while(root!=NULL){//traverse a layer of nodes and add the child nodes of that layer node from left to right to the next layer if(root.left!=NULL) {Curchild.next=Root.left; Curchild=Curchild.next; } if(root.right!=NULL) {Curchild.next=Root.right; Curchild=Curchild.next; } Root=Root.next; } Root= Tempchild.next;//load the first node of the next layer to root and traverse the next layer } }}
[Leetcode] 117. Populating Next right pointers in each Node II Java