码迷,mamicode.com
首页 > 其他好文 > 详细

Populating Next Right Pointers in Each Node

时间:2014-11-29 15:47:58      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   strong   on   

编程小记,已供重温!!

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

标签:style   blog   io   ar   color   sp   for   strong   on   

原文地址:http://www.cnblogs.com/hitkb/p/4130975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!