首页 > 其他 > 详细

116. Populating Next Right Pointers in Each Node

时间:2019-03-11 12:23:17      阅读:146      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!