Simple preorder traversal with lvl in Java


  • 1
    L
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> ans = new ArrayList<>();
            rightSideView(root, 1, ans);
            return ans;
        }
        
        private void rightSideView(TreeNode node, int lvl, List<Integer> ans) {
            if (node == null) return;
            if (lvl > ans.size()) ans.add(node.val);
            else ans.set(lvl - 1, node.val);
            rightSideView(node.left, lvl + 1, ans);
            rightSideView(node.right, lvl + 1, ans);
        }
    }

Log in to reply
 

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