二叉树-populate next node

来源:互联网 发布:java 首字母小写 编辑:程序博客网 时间:2024/05/21 18:40
2014.8.17 update:
可以利用linkelist里面fake node的思想来链接下一层node:
    public void connect(TreeLinkNode root) {        if (root == null) {            return;        }        TreeLinkNode cur = root;                while(cur != null) {            TreeLinkNode nextHead = new TreeLinkNode(0);            TreeLinkNode nextCur = nextHead;                        while (cur != null) {                if (cur.left != null) {                    nextCur.next = cur.left;                    nextCur = nextCur.next;                }                if (cur.right != null) {                    nextCur.next = cur.right;                    nextCur = nextCur.next;                }                cur = cur.next;            }            cur = nextHead.next;        }        



// populating next node when tree is balanced
public class Solution {
    public voidconnect(TreeLinkNode root) {
   
       TreeLinkNode leftNode = root;
       while (leftNode != null) {

          TreeLinkNode node = leftNode;
           while(node != null) {
              if (node.left != null){
                 node.left.next = node.right;
              }
              if (node.next != null&& node.right != null) {
                 node.right.next = node.next.left;
              }
              node = node.next;
           }
           leftNode =leftNode.left;
       }
    }
}

// unbalanced tree populating next node
public class Solution {
    public voidconnect(TreeLinkNode root) {

       TreeLinkNode leftNode = root;
       TreeLinkNode nextBegin;
       TreeLinkNode nextEnd;

       while (leftNode != null) {

          TreeLinkNode node = leftNode;
           nextBegin= null;
           nextEnd =null;
           while(node != null) {
              while (nextBegin == null&& node != null) {
                 if (node.left != null) {
                     nextBegin= node.left;
                     if(node.right != null) {
                        node.left.next =node.right;
                        nextEnd = node.right;
                     } else{
                        nextEnd = nextBegin;
                     }
                     node =node.next;
                    break;
                 } else if (node.right != null) {
                     nextBegin= node.right;
                     nextEnd =node.right;
                     node =node.next;
                    break;
                 }
                 node = node.next;
              }
              if (node != null) {
                 if (node.left != null) {
                    nextEnd.next = node.left;
                     nextEnd =nextEnd.next;
                 }
                 if (node.right != null) {
                    nextEnd.next = node.right;
                     nextEnd =nextEnd.next;
                 }
                 node = node.next;
              }
           }
           leftNode =nextBegin;
       }
    }
}
0 0
原创粉丝点击