首页 > 代码库 > Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

编程小记,已供重温!!

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



此题,我的第一反映是广度优先遍历。按层访问。每一层自左向右按顺序链接!需要借助于队列来实现。但是没有去实现。
思路二是,我们仔细观察发现,链接分为2种情况:情况1是链接root节点的左子树与右子树。情况2是链接节点2的右子树与节点3的左子树。
         1                                2   ——》   3                                     /  \                             /  \       /         2 -> 3                           4    5 ——》 6    7
(1) (2)
剩余的就是选择一个普通的遍历方式。
public static void tra(TreeLinkNode root) {        if (root == null) {            return;        }        Stack<TreeLinkNode> stack = new Stack<>();        while (null != root || !stack.isEmpty()) {            while (null != root) {                stack.push(root);
          //visit
          System.out.println(root.val);
          //   root
= root.left; } root = stack.pop(); root = root.right; } }

遍历的同时,链接2种。

public static void connect(TreeLinkNode root) {        if (root == null) {            return;        }        Stack<TreeLinkNode> stack = new Stack<>();        while (null != root || !stack.isEmpty()) {            while (null != root) {                stack.push(root);                if (root.left != null) {                    root.left.next = root.right;                    if (root.next != null) {                        root.right.next = root.next.left;                    }                }                root = root.left;            }            root = stack.pop();            root = root.right;        }    }

 



Populating Next Right Pointers in Each Node