LeetCode(116) Populating Next Right Pointers in Each Node

来源:互联网 发布:arttemplate.js api 编辑:程序博客网 时间:2024/06/05 00:31

题目如下:

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *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.

Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
         1
       /    \
      2     3
     / \     / \
    4  5  6  7
After calling your function, the tree should look like:
           1  -> NULL
       /        \
      2   ->  3 -> NULL
     / \         / \
    4->5-> 6->7 -> NULL

分析如下:

对每个节点,做2个任务。

1. 把它的left child的next指向right child,就完成了left child的next指针的populate.如上图中的2->3, 4->5,6->7,

2. 对于right child的next指针的populate,如5->6,需要right child 指针parent ->next->left.

接下来递归,对当前节点的left child和right child做和上面相同的任务。

我的代码:

/** * Definition for binary tree with next pointer. * struct TreeLinkNode { *  int val; *  TreeLinkNode *left, *right, *next; *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public:    void connect(TreeLinkNode *root) {        if (root == NULL) return;        if (root->next && root->right)             root->right->next= root->next->left;        if (root->left)            root->left->next = root->right;        connect(root->left);//line 18        connect(root->right);//line 19        //line 18 和line 19顺序可以换,因为这是perfect binary tree.    }};
扩展阅读:

这道题目中的connect(root->left)和connect(root->right)的顺序可以互换。但是,下一道题目,条件由perfect binary tree变化为了any binary tree,所以这两行顺序只能是

1. connect(root->right);

2. connect(root->left);

详见下一道题目。

0 0
原创粉丝点击