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
题目含义:给定一个完全二叉树,从左到右连接每一层节点.
完全二叉树:所有叶子都在同一深度,每一个根节点都有两个叶子节点
方法一:
1     public void connect(TreeLinkNode root) {
2 //        由于是完全二叉树,所以若节点的左子结点存在的话,其右子节点必定存在,所以左子结点的next指针可以直接指向其右子节点,对于其右子节点的处理方法是,判断其父节点的next是否为空,若不为空,则指向其next指针指向的节点的左子结点,若为空则指向NULL
3          if (root ==null ) return;
4          if (root.left != null) root.left.next = root.right;
5          if (root.right!=null) root.right.next = root.next!=null?root.next.left :null;
6          connect(root.left);
7          connect(root.right);     
8     }

方法二:会超时

复制代码
 1     public void connect(TreeLinkNode root) {
 2         List<Integer> result = new ArrayList<>();
 3         if (root == null) return;
 4         Queue<TreeLinkNode> q = new LinkedList<>();
 5         q.add(root);
 6         while (!q.isEmpty()) {
 7             int size = q.size();
 8             TreeLinkNode prev = null;
 9             TreeLinkNode cur = null;
10             for (int i = 0; i < size - 1; i++) {
11                 cur = q.poll();
12                 if (prev == null) {
13                     prev = cur;
14                 } else {
15                     prev.next = cur;
16                     prev = cur;
17                 }
18 
19                 if (cur.left != null) q.offer(cur.left);
20                 if (cur.right != null) q.offer(cur.right);
21             }
22         }
23     }
复制代码

 

posted @   daniel456  阅读(121)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示