Simple Java solution using Two Queues


  • 0
    J
     if(root==null)return Collections.emptyList();
            LinkedList<TreeNode> que1=new LinkedList<TreeNode>();
            LinkedList<TreeNode> que2=new LinkedList<TreeNode>();
            List<Integer> res=new ArrayList<Integer>();
            que1.add(root);
            
            while(!que1.isEmpty()){
                res.add(que1.peekLast().val);
                while(!que1.isEmpty()){
                    TreeNode cur=que1.poll();
                    if(cur.left!=null)que2.add(cur.left);
                    if(cur.right!=null)que2.add(cur.right);
                }
                que1=que2;
                que2=new LinkedList<TreeNode>();
            }
            return res;

Log in to reply
 

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