Populating Next Right Pointers in Each Node (LeetCode)

来源:互联网 发布:java微信二次开发视频 编辑:程序博客网 时间:2024/06/14 06:40

题目:

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


题目分析:

题目中给出一个完美二叉树。每个节点有left、right、next三个指针。left、right已经给好。要求将next指向自己右边的兄弟节点。如果已经是最右边,则指向null。





思路:

  1. 使用广度优先遍历二叉树
    • 建立一个队列queue,每次将节点的左孩子、右孩子分别放入queue中。
    • 下一个需要遍历的点,即为queue中的头结点。
  2. 用tag标记所在层的最右边的节点。
  3. 遍历到tag之前,将所在节点的next指向queue中的头结点
  4. 遍历到tag时,把next指向null,左孩子、右孩子入队列。将tag的右孩子标记为tag。




注意点:

  1. 要注意queue接口的用法。
  2. queue中,poll和remove的区别



代码:

/** * Definition for binary tree with next pointer. * public class TreeLinkNode { *     int val; *     TreeLinkNode left, right, next; *     TreeLinkNode(int x) { val = x; } * } */import java.util.*;public class Solution {    public void connect(TreeLinkNode root) {        if (root == null){            return;        }        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();        TreeLinkNode tag = root;        TreeLinkNode thisNode = root;        while (thisNode != null){            if (thisNode == tag){                if (thisNode.left != null){                    queue.add(thisNode.left);                    queue.add(thisNode.right);                    tag = thisNode.right;                }                thisNode.next = null;                thisNode = queue.poll();            }else{                thisNode.next = queue.poll();                if (thisNode.left != null){                    queue.add(thisNode.left);                    queue.add(thisNode.right);                }                thisNode = thisNode.next;            }        }    }}




0 0
原创粉丝点击