LeetCode-116. Populating Next Right Pointers in Each Node (JAVA)

来源:互联网 发布:泗阳网络直通车 编辑:程序博客网 时间:2024/06/05 18:09

116. Populating Next Right Pointers in Each Node

填充每一个节点的指向右边邻居的指针I

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 toNULL.

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
  • 你只能使用常数级别的额外空间
  • 你可以假设该树为完全二叉树(即所有叶子节点都在同一层,而且每个父节点都有两个子节点)。
树的广度优先搜索题。记录下每一层的节点总个数,然后根据广度优先搜索的原则进行遍历,将非null节点都加入到队列中,对于同一层中的节点,将其next指向队列中的下一个节点即可。

队列+BFS

public void connect(TreeLinkNode root) {if (root == null)return;// 需要获得第一个node使用双端队列Deque<TreeLinkNode> dq = new LinkedList<>();dq.addLast(root);int curNum = 1;while (!dq.isEmpty()) {TreeLinkNode node = dq.removeFirst();curNum--;if (node.left != null)dq.addLast(node.left);if (node.right != null)dq.addLast(node.right);if (curNum > 0)node.next = dq.getFirst();elsecurNum = dq.size();}}

递归

// O(n) time, O(logn) spacepublic void connect(TreeLinkNode root) {if (root == null)return;if (root.left != null) {root.left.next = root.right;// 如果左子树不空,那么右子树不空,因为每个都有两个孩子// every parent has two childrenif (root.next != null)root.right.next = root.next.left;}connect(root.left);connect(root.right);}

递归2

// O(n) time, O(logn) spacepublic void connect(TreeLinkNode root) {if (root == null)return;connect(root.left, root.right);}private void connect(TreeLinkNode left, TreeLinkNode right) {if (left == null)return;// 以下if可省,但是递归深度增大// 没有运行时间是4ms,加了是1msif (left.next == right)return;left.next = right;// left.left.next = left.right;connect(left.left, left.right);// left.right.next=right.leftconnect(left.right, right.left);// right.left.next=right.rightconnect(right.left, right.right);}

top解法

// O(1) memory+ O(n) time// 类似BFS(层次)public void connect(TreeLinkNode root) {if (root == null)return;TreeLinkNode cur = root;TreeLinkNode nextLeftmost = null;while (cur.left != null) {// save the start of next level// 保存下一层最左侧结点nextLeftmost = cur.left;while (cur != null) {cur.left.next = cur.right;cur.right.next = cur.next == null ? null : cur.next.left;// same as if (cur.next != null)// cur.right.next = cur.next.left;cur = cur.next;}// point to next level// 指向下一层结点,继续遍历cur = nextLeftmost;}}}




0 0
原创粉丝点击