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     }

  • 相关阅读:
    hdu 5154 拓扑排序
    CSS性能优化的8个技巧
    移动端性能监控方案Hertz
    箴言
    如何使网页的文字不能被复制
    flyio 的请求封装
    vue-cli3.0 环境变量与模式
    函数防抖和函数节流
    CSS世界中那些说起来很冷的知识
    vue多层次组件监听动作和属性
  • 原文地址:https://www.cnblogs.com/springfor/p/3887681.html
Copyright © 2011-2022 走看看