My straight-forward Iterative Solution, layer by layer (JAVA)


  • 0

    The basic idea is to get all the children in the next layer, store the last child, and then put all the children of the next layer's nodes.

    public class Solution {
      List<Integer> ret;
      public List<Integer> rightSideView(TreeNode root) {
        ret = new ArrayList<Integer>();
        List<TreeNode> tmp = new ArrayList<TreeNode>();
        if(root!=null)
          tmp.add(root);
        getRight(tmp);
        return ret;
      }
      private void getRight(List<TreeNode> tmp){
        if(tmp.size()==0) return;
        //Get the last element in the array
        ret.add(tmp.get(tmp.size()-1).val);
        //Put all the left/right child in the new array
        List<TreeNode> tmp2 = new ArrayList<TreeNode>();
        for(TreeNode x:tmp){
          if(x.left!=null) tmp2.add(x.left);
          if(x.right!=null) tmp2.add(x.right);
        }
        getRight(tmp2);
      }
    }

Log in to reply
 

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