专栏首页计算机视觉与深度学习基础Leetcode 116 Populating Next Right Pointers in Each Node

Leetcode 116 Populating Next Right Pointers in Each Node

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

将二叉树的每一层节点从左至右连接起来。

可以用层序遍历,也可以深搜。

/**
 * 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 ;
        if(root->left) 
        {
            root->left->next=root->right;
            connect(root->left);
        }
        if(root->right) 
        {
            if(root->next) root->right->next=root->next->left;
            connect(root->right);
        }
    }
};

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Leetcode 101 Symmetric Tree

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric arou...

    triplebee
  • Leetcode 226. Invert Binary Tree

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to ...

    triplebee
  • Leetcode 214. Shortest Palindrome

    Given a string S, you are allowed to convert it to a palindrome by adding chara...

    triplebee
  • 【leetcode】Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node".

    阳光岛主
  • LeetCode 129 Sum Root to Leaf Numbers

    ShenduCC
  • LeetCode 257. Binary Tree Paths

    ShenduCC
  • 小白配环境

    一、Conda配置1.Path配置2.Anaconda prompt配置3.Anaconda Navigator二、Python2与Python3切换1.Ana...

    公众号guangcity
  • 那些你可能不了解的公有云风险成本

    公有云强调了给企业带来的种种好处,但是它并不十全十美。企业应该意识到其不可预测的成本结构以及其他的一些缺点。 ? 公有云服务给予企业诸多优势。他们允许灵活和经济...

    静一
  • [剑指offer] 合并两个排序的链表

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

    尾尾部落
  • 这个比马尔代夫还美的岛,上云了!

    ? 今日获悉,腾讯云以1个亿中标福建平潭全域智慧旅游一期工程,双方将联手打造全国首个科技+文旅融合智慧国际旅游岛。 作为中国三大国际旅游岛之一,平潭岛被官方盖...

    腾讯文旅

扫码关注云+社区

领取腾讯云代金券