码迷,mamicode.com
首页 > 其他好文 > 详细

116. Populating Next Right Pointers in Each Node

时间:2019-03-11 11:54:35      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:binary   set   父节点   child   evel   pre   src   color   init   

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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.

 

Example:

技术图片

 

网上找到比较好的讲解是来自 https://segmentfault.com/a/1190000003465911

1. 先来递归的

思路

由于父节点多了next指针,我们不用记录父节点的父节点就能直到它相邻的节点。对于左子节点来说,其next节点就是父节点的右节点。对于右子节点来说i,其next节点就是父节点的next节点的左子节点。以此递归。

// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val,Node _left,Node _right,Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
class Solution {
    public Node connect(Node root) {
                Node level_start=root;
        while(level_start!=null){
            Node cur=level_start;
            while(cur!=null){
                if(cur.left!=null) cur.left.next=cur.right;
                if(cur.right!=null && cur.next!=null) cur.right.next=cur.next.left;
                
                cur=cur.next;
            }
            level_start=level_start.left;
        }
        return root;
    }
}

 

116. Populating Next Right Pointers in Each Node

标签:binary   set   父节点   child   evel   pre   src   color   init   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10509641.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!