Java BFS solution


  • 0
    /**
     * 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 static class HeightedNode{
            int height;
            TreeLinkNode node;
            public HeightedNode(TreeLinkNode node, int height) {
                this.node = node;
                this.height = height;
            }
        }
        public void connect(TreeLinkNode root) {
            if(root == null) {
                return;
            }
            Queue<HeightedNode> queue = new LinkedList<HeightedNode>();
            queue.add(new HeightedNode(root, 0));
            HeightedNode last = null;
            while (queue.size() != 0) {
                HeightedNode n = queue.remove();
                
                if(last != null && last.height == n.height) {
                    last.node.next = n.node;
                }
                
                if(n.node.left != null) {
                    queue.add(new HeightedNode(n.node.left, n.height + 1));
                }
                if(n.node.right != null) {
                    queue.add(new HeightedNode(n.node.right, n.height + 1));
                }
                last = n;
            }
        }
    }
    

  • 0
    M

    The question states that you have to use a constant space. So, I don't think you can use a queue.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.