zoukankan      html  css  js  c++  java
  • Populating Next Right Pointers in Each Node leetcode java

    题目

    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
    
    题解

    这道题解法还是挺直白的,如果当前节点有左孩子,那么左孩子的next就指向右孩子。如果当前节点有右孩子,那么判断,如果当前节点的next是null,
    说明当前节点已经到了最右边,那么右孩子也是最右边的,所以右孩子指向null。如果当前节点的next不是null,那么当前节点的右孩子的next就需要
    指向当前节点next的左孩子。
    递归求解就好。

    代码如下:
     1     public void connect(TreeLinkNode root) {
     2         if(root==null)
     3             return;
     4         if(root.left!=null)
     5             root.left.next=root.right;
     6         if(root.right!=null){
     7             if(root.next!=null)
     8                 root.right.next = root.next.left;
     9             else
    10                 root.right.next = null;
    11         }
    12         connect(root.left);
    13         connect(root.right);
    14     }

  • 相关阅读:
    【leetcode】腾讯精选练习 50 题(更新中)
    将博客搬至CSDN
    【笔记】linux基础(更新中)
    【寒窑赋】写在百篇博客之后
    【笔记】Vim
    【笔记】Git(更新中)
    【笔记】Java基础教程学习(更新中)
    【面试题】Java核心技术三十六讲(更新中)
    【leetcode】shell和sql题目思路汇总(更新中)
    【笔记】MySQL基础及高级特性(更新中)
  • 原文地址:https://www.cnblogs.com/springfor/p/3887681.html
Copyright © 2011-2022 走看看