Given a binary tree

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

 

Follow up:

  • You may only use constant extra space.
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

 

Example 1:

Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next


思路:这道题的思路是:
1. 如果root 根是null 则返回一个null
2. 如果root 有左子树 且有右子树 则左子树和右子树向连接
3. 如果root 有左子树 没有右子树 则查看root 的next 是否有左子树和右子树 然后和之前的左子树连接
4. 然后用递归以此类推
struct Node* dfs(struct Node* root)
{
    if(root == NULL) return NULL;
    if(root->left) return root->left;
    if(root->right) return root->right;
    return dfs(root->next);
    
}


struct Node* connect(struct Node* root) {
    if(root == NULL)
        return;
    if(root->left != NULL)
    {
        if(root->right != NULL)
        {
            root->left->next = root->right;
            
            
        }
        else
            root->left->next = dfs(root->next);
        
    }
    if(root->right != NULL)
    {
        root->right->next = dfs(root->next);
    }
    
    connect(root->right);
    connect(root->left);
    return root;
    
}

 

posted on 2020-04-29 05:23  闲云潭影  阅读(125)  评论(0编辑  收藏  举报