117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:新浪微博下载mac版 编辑:程序博客网 时间:2024/06/05 00:37

题目:Populating Next Right Pointers in Each Node II

原题链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
Follow up for problem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For example,
Given the following binary tree,
p3
After calling your function, the tree should look like:
p4

给出一个二叉树,让每层节点的next()指向其右边一个节点,每层最右节点指向NULL,初始next()都指向NULL。
注意:只能使用常数级额外空间。

和116题不同,这次不保证是一个完全二叉树了,只能用一般性的方法,层序遍历二叉树,每层的最右节点外,其余节点都指向层序遍历的下一个节点。

代码如下:

/** * 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) return;        queue<TreeLinkNode*> q;        q.push(root);        // left表示每层的最左节点,pre表示取出的节点的前一个节点        TreeLinkNode *left = root, *pre;         bool le = false; // 用来指示下一层的最左节点是否已经找到        while(!q.empty()) {            TreeLinkNode* t = q.front();            q.pop();            if(t == left) {                le = false;            } else {                pre->next = t;            }            if(t->left) {                if(!le) {                    left = t->left;                    le = true;                }                q.push(t->left);            }            if(t->right) {                if(!le) {                    left = t->right;                    le = true;                }                q.push(t->right);            }            pre = t;        }        return;    }};
0 0
原创粉丝点击