[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

一般的做法,利用BFS对同层进行扫描,然后增加位置关系,并在一层扫描完毕后进行判断。为了判断是否跳层,新增了一个自定义类型。

public class Solution {
     public void connect(TreeLinkNode root) {
        if(root == null) return;
        Queue<myTreeLinkNode> queue = new LinkedList<>();
        myTreeLinkNode treeLinkNodeRoot = new myTreeLinkNode(root, 0);
        myTreeLinkNode tmp, lastTreeLinkNode = null;
        int currentLevel = 0;
        queue.add(treeLinkNodeRoot);
        while(!queue.isEmpty()){
            tmp = queue.poll();
            if(tmp == treeLinkNodeRoot)
                lastTreeLinkNode = tmp;
            else{
                if(currentLevel != tmp.level){
                    currentLevel = tmp.level;
                }else{
                    lastTreeLinkNode.treeLinkNode.next =
                            tmp.treeLinkNode;
                }
                lastTreeLinkNode = tmp;
            }
            if(tmp.treeLinkNode.left != null)
                queue.add(new myTreeLinkNode(tmp.treeLinkNode.left,
                        tmp.level + 1));
            if(tmp.treeLinkNode.right != null)
                queue.add(new myTreeLinkNode(tmp.treeLinkNode.right,
                        tmp.level + 1));
        }
    }

    class myTreeLinkNode {
        TreeLinkNode treeLinkNode;
        int level;
        myTreeLinkNode(TreeLinkNode node, int l){
            this.treeLinkNode = node;
            this.level = l;
        }
    }
}

之前的博文就有提到过对队列的操作十分耗时,因此这里给出一个比较难以理解的递归方法,实现起来十分的优雅,很值得学习。

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null)
            return;
        connect(root.left);
        connect(root.right);
        connect(root.left, root.right);
    }

    public void connect(TreeLinkNode left, TreeLinkNode right) {
        while (left != null) {
            left.next = right;
            left = left.right;
            right = right.left;
        }
    }
}

题目链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

你可能感兴趣的:(LeetCode)