Simple and concise level-order traversal implementation of java.


  • 0
    W

    '''

    public class Solution {

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        levelTraversal(result, root, 1);
        return result;
    }
    
    public void levelTraversal(List<Integer> result, TreeNode root, int level) {
        if (root == null) return;
        
        if(level > result.size()) {
            result.add(root.val);
        }else{
            result.set(level - 1, root.val);
        }
        
        levelTraversal(result, root.left, level + 1);
        levelTraversal(result, root.right, level + 1);
        
    }
    

    }


Log in to reply
 

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