LeetCode算法题目:Populating Next Right Pointers in Each Node II

来源:互联网 发布:js给input文本框赋值 编辑:程序博客网 时间:2024/06/07 01:29

题目:

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,
这里写图片描述
After calling your function, the tree should look like:
这里写图片描述

分析:

本题目是Populating Next Right Pointers in Each Node( 每个节点的右向指针)的延续,原本的完全二叉树的条件不再满足,但是整体的思路还是很相似,这里由于子树有可能残缺,故需要平行扫描父节点同层的节点,找到他们的左右子节点。

代码:

/** * 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;        TreeLinkNode *p = root->next;        while (p) {            if (p->left) {                p = p->left;                break;            }            if (p->right) {                p = p->right;                break;            }            p = p->next;        }        if (root->right) root->right->next = p;         if (root->left) root->left->next = root->right ? root->right : p;         connect(root->right);        connect(root->left);    }};
1 0
原创粉丝点击