Describe:
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
Ideas:
is to use two list to store the adjacent two-layer node, the I+1 layer node is stored in the list, respectively, the first layer of each node points to the next, with 116 populating next right pointers in every node I a thought, do not repeat the writing.
Code:
/** * Definition for binary tree with next pointer. * public class Treelinknode {* int val; * Treelinknode left, right, next; * Treelinknode (int x) {val = x;} *} */public class Solution {public void connect (Treelinknode root) {if (root==null) return; List<treelinknode>list=new arraylist<treelinknode> (); List<treelinknode>temp=new arraylist<treelinknode> (); Treelinknode Node=null,tempnode=null; List.add (root); while (true) {tempnode=list.get (0); if (tempnode.left!=null) Temp.add (tempnode.left); if (tempnode.right!=null) Temp.add (tempnode.right); for (int i=1;i<list.size (); i++) {node=list.get (i); if (node.left!=null) Temp.add (node.left); if (node.right!=null) Temp.add (node.right); Tempnode.next=node; Tempnode=node; } if (Temp.size ()!=0) {list=temp; Temp=new arraylist<treelinknode> (); } else BReak; } return; }}
Results:
Leetcode_117_populating Next Right pointers in each Node II