Leetcode_populating-next-right-pointers-in-each-node-ii(updated c++ version)

62 篇文章 0 订阅
52 篇文章 0 订阅

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,

         1
       /  \
      2    3
     / \    \
    4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL

思路:
在遍历第 x 层节点时,确定 x+1层节点的 next 关系
用指针last记录上一个节点,并通过更新last来形成节点的next关系
nxt记录下一层的第一个节点
参考代码:
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(!root)
            return;
        TreeLinkNode *p = root, *last = NULL, *nxt = NULL;
        while(p)
        {
            if(p->left)
            {
                if(!last)
                    last = p->left;
                else
                    last = last->next = p->left;
                if(!nxt)
                    nxt = p->left;
            }
            if(p->right)
            {
                if(!last)
                    last = p->right;
                else
                    last = last->next = p->right;
                if(!nxt)
                    nxt = p->right;
            }
            p = p->next;
        }
        connect(nxt);
    }
};



思路:用python里的dictionary,类似c++的map,代码实现需要一点trick,有额外空间
参考代码:
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree node
    # @return nothing
    def connect(self, root):
        if not root: return
        s={0: [root]}
        cur = 0
        while 1:
            if not s.has_key(cur):
                break
            li = s[cur]
            for i in li:
                if i.left:
                    if s.has_key(cur+1):
                        s[cur+1][-1].next = i.left
                        s[cur+1].append(i.left)
                    else:
                        s[cur+1] = [i.left]
                if i.right:
                    if s.has_key(cur+1):
                        s[cur+1][-1].next = i.right
                        s[cur+1].append(i.right)
                    else:
                        s[cur+1] = [i.right]
            cur += 1
        return
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值