Programming little memory, has been for review!! Populating Next right pointers in each Node
Given a binary tree
struct Treelinknode { treelinknode *left; Treelinknode *right; Treelinknode *next; }
Populate each of the next pointer to the next right node. If There is no next right node, the next pointer should are set to NULL .
Initially, all next pointers is set to NULL .
Note:
- Constant extra space.
- You could assume that it was a perfect binary tree (ie, all leaves was at the same level, and every parent had both children).
For example,
Given the following perfect binary tree,
1 / 2 3 /\ / 4 5 6 7
After calling your function, the tree is should look like:
1, NULL / 2, 3, null /\ / 4-> 5->6, 7, NULL
This question, my first reflection is breadth-first traversal. accessed by layer. Each layer is linked from left to right sequentially! Need to be implemented by queues. But not to achieve.
Second, we carefully observed that the link is divided into 2 cases: Case 1 is the Zuozi and right subtree of the link root node. Case 2 is the right subtree of link Node 2 with the left subtree of node 3.
1 2 --" 3 / \ / \ / 2, 3 4 5--" 6 7
(1) (2)
The rest is to choose a normal traversal mode.
Public Static voidtra (treelinknode root) {if(Root = =NULL) { return; } Stack<TreeLinkNode> stack =NewStack<>(); while(NULL! = Root | | !Stack.isempty ()) { while(NULL!=Root) {Stack.push (root);
Visit
System.out.println (Root.val);
Root=Root.left; } Root=Stack.pop ();Root =Root.right; } }
Traverse the same time, link 2 kinds.
Public Static voidConnect (Treelinknode root) {if(Root = =NULL) { return; } Stack<TreeLinkNode> stack =NewStack<>(); while(NULL! = Root | | !Stack.isempty ()) { while(NULL!=root) {Stack.push (root); if (root.left! = null) {Root.left.next = Root.right; if (root.next! = null) {Root.right.next = Root.next.left; }} Root=Root.left; } Root=Stack.pop (); Root=Root.right; } }
Populating Next right pointers in each Node