Follow up for problem"Populating next right pointers in each node".
What if the given tree cocould be any binary tree? Wocould your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / 2 3 / \ 4 5 7
After calling your function, the tree shoshould look like:
1-> null/2-> 3-> null/\ 4-> 5-> 7-> null
Algorithm: This is the same as the variant of the first question. First, we only need to consider the current node and then perform recursion. The key points are as follows: 1. When the left subtree of the node or the first node on the right of the right subtree 2. recursion, calculate the right subtree first, because the result on the right is used for processing recursion in the left subtree, the Code is as follows:
1 /** 2 * Definition for binary tree with next pointer. 3 * struct TreeLinkNode { 4 * int val; 5 * TreeLinkNode *left, *right, *next; 6 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 void connect(TreeLinkNode *root) {12 if(NULL==root) return;13 if(NULL!=root->left)14 {15 if(NULL!=root->right)16 {17 root->left->next=root->right;18 }19 else root->left->next=find(root->next);20 }21 if(NULL!=root->right)22 {23 root->right->next=find(root->next);24 }25 26 27 connect(root->right);28 connect(root->left);29 }30 31 TreeLinkNode* find(TreeLinkNode *temp)32 {33 if(NULL==temp) return NULL;34 while(NULL!=temp)35 {36 if(NULL!=temp->left) return temp->left;37 else if(NULL!=temp->right) return temp->right;38 else temp=temp->next;39 }40 return NULL;41 }42 };
Populating next right pointers in each node II <leetcode>