My level order traversal solution(JAVA)


  • 0
    M
    public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new LinkedList<Integer>();
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        
        if (root == null) return result;
        q.offer(root);
        while (!q.isEmpty()){
            int n = q.size();
            int temp = 0;
            for (int i = 0; i < n; i += 1){
                if (q.peek().left != null) q.offer(q.peek().left);
                if (q.peek().right != null) q.offer(q.peek().right);
                temp = q.poll().val;
            }
            result.add(temp);
        }
        return result;
    }
    

    }

    Traverse each level and keep the val from the right most node.


  • 0
    B
    This post is deleted!

Log in to reply
 

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