Populating Next Right Pointers in Each Node II

来源:互联网 发布:波士顿房价数据集 编辑:程序博客网 时间:2024/05/21 08:10

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1       /  \      2    3     / \    \    4   5    7

After calling your function, the tree should look like:

         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 7 -> NULL

思路:利用一个 ArrayList 来存储next  level node. So the node.next is the node in the arraylist next node.
易错点:每一层一定要把 ArrayList 清空。
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { *     int val; *     TreeLinkNode left, right, next; *     TreeLinkNode(int x) { val = x; } * } */public class Solution {    public void connect(TreeLinkNode root) {        if(root == null)            return;        List<TreeLinkNode> cur = new ArrayList<TreeLinkNode>();        cur.add(root);        while(true){            List<TreeLinkNode> pre = new ArrayList<TreeLinkNode>(cur);            cur.clear();            for(int i = 0; i < pre.size(); i++){                if(i < pre.size() - 1){                    pre.get(i).next = pre.get(i + 1);                }else{                    pre.get(i).next = null;                }            }            for(TreeLinkNode node : pre){                if(node.left != null)                    cur.add(node.left);                if(node.right != null)                    cur.add(node.right);            }            if(cur.size() < 1)                break;        }    }}


0 0
原创粉丝点击