Populating Next Right Pointers in Each Node

来源:互联网 发布:mac页面如何放大 编辑:程序博客网 时间:2024/05/29 11:47

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
Tree Depth-first Search

题解:
1.每个节点的next都指向NULL;
2.使用有限的空间;
3.可假定它是完全二叉树。

思路:
递归方法。如下:

class Solution {public:    void connect(TreeLinkNode *root) {        if (root == NULL)            return;        TreeLinkNode *left, *right;        left = root->left;        right = root->right;        if (left != NULL)            left->next = right;        /*右子数不空,则指向另一个父结点的左子树*/        if (right != NULL && root->next != NULL)            right->next = root->next->left;        connect(left);        connect(right);    }};

思路:
非递归之循环。如下:

   void connect(TreeLinkNode *root) {        if (root == NULL)            return;        TreeLinkNode *current;        while (root->left){        //因为题目假设都为完全二叉树,此判断只需确定是否为叶子结点            current = root;            while (current){                current->left->next = current->right;                if (current->right && current->next)                    current->right->next = current->next->left;                current = current->next;            }            root = root->left;        }    }
0 0