2014年10月18日星期六

[Leetcode] 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
使用和Populating Next Right Pointers in Each Node II一样的方法就可以了,也可以使用递归的方法,在两个节点上递归,先把同一个节点上的左右节点连接在一起,然后在把左边的右子树和右边的左子树连接在一起。
    public void connect(TreeLinkNode root) {
        while(root != null) {
            TreeLinkNode next = null, pre = null;
            for(; root != null; root = root.next) {
                if(next == null) next = root.left == null ? root.right : root.left;
                if(root.left != null) {
                    if(pre != null) pre.next = root.left;
                    pre = root.left;
                }
                if(root.right != null) {
                    if(pre != null) pre.next = root.right;
                    pre = root.right;
                }
            }
            root = next;
        }
    }

没有评论:

发表评论