Level-Order Traversal (Java Solution)


  • 0
    S

    A simple level-order traversal will do the favor.
    The space used is the maximum size of a layer.

    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            List<TreeNode> cur_layer = new ArrayList<TreeNode>();
            
            // edge case
            if(root==null) return list;
            
            // initialize current layer
            cur_layer.add(root);
            
            // level-order traversal
            while(!cur_layer.isEmpty()){
                list.add(cur_layer.get(cur_layer.size()-1).val);
                List<TreeNode> next_layer = new ArrayList<TreeNode>();
                for(TreeNode node: cur_layer){
                    if(node.left!=null) next_layer.add(node.left);
                    if(node.right!=null) next_layer.add(node.right);
                }
                cur_layer = next_layer;
            }
            
            return list;
        }
        
    }

  • 0
    S
     public List<Integer> rightSideView(TreeNode root) {
       
       List<Integer> results = new LinkedList<>();
        
       if(root == null) {
            return results;
        }
    
        Queue<TreeNode> level = new LinkedList<>();
        Queue<TreeNode> nextLevel = new LinkedList<>();
       
        level.add(root);
        
        while(!level.isEmpty()) {
            TreeNode tn = level.poll();
    
            if(tn.left != null) {
                nextLevel.add(tn.left);
            }
    
           if(tn.right != null) {
               nextLevel.add(tn.right);
            }
           
           if(level.isEmpty()) {
               level = nextLevel;
               nextLevel = new LinkedList<>();
               results.add(tn.val);
           }
        }
      return results;
    }

Log in to reply
 

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