A weird java solution


  • 0
    S
    public class Solution {
        public List<Integer> largestValues(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            Queue<TreeNode> q = new LinkedList<>();
            Queue<TreeNode> q2 = new LinkedList<>(), tempQ;
            TreeNode temp;
            
            if (root != null)
                q.add(root);
            while (!q.isEmpty()) {
                Integer max = null;
                while(!q.isEmpty()) {
                    temp = q.poll();
                    if (max == null)
                        max = temp.val;
                    else
                        max = Math.max(max, temp.val);
                    if (temp.left != null)
                        q2.add(temp.left);
                    if (temp.right != null)
                        q2.add(temp.right);
                }
                result.add(max);
                tempQ = q;
                q = q2;
                q2 = tempQ;
            }
            return result;
        }
    }

Log in to reply
 

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