Another way of adding the leaves nodes


  • 0
    D

    Re: [Java(12ms) - left boundary](left leaves)

    Another way of doing it without calling leaves twice.
    '''

    List<Integer> ls = new ArrayList<Integer>();
    
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        if (root == null) return ls;
        else ls.add(root.val);
        if(root.left != null) leftTraversal(root.left);
        if (root.left!=null || root.right!=null) getChilds(root);
        if (root.right!=null){rightTraversal(root.right);}
        return ls;
    }
    
    public void leftTraversal(TreeNode node){
        
        if ( node == null ||(node.left == null && node.right == null)){
            return;
        }
        else{
            ls.add(node.val);
            System.out.println(node.val);
            if (node.left!= null) leftTraversal(node.left);
            else leftTraversal(node.right);
        }
    }
    
    public void getChilds(TreeNode node){
        if(node==null) return;
        else if (node.left == null && node.right==null){
            ls.add(node.val);
            return;
        }
        else{
            getChilds(node.left);
            getChilds(node.right);
        }
    }
    
    public void rightTraversal(TreeNode node){
     
        if (node == null ||(node.left == null && node.right == null)){
            return;
        }
        else{
            if (node.right!= null) rightTraversal(node.right);
            else rightTraversal(node.left);
            ls.add(node.val);
        }
    }

Log in to reply
 

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