JavaScript Solution using Recursion


  • 0
    N
    var boundaryOfBinaryTree = function(root) {
        var result = [];
        
        if(root !== null) {
           result.push(root.val);
           findBoundary(root.left, result, true, false); 
           findBoundary(root.right, result, false, true); 
        }
        
        return result;  
    };
    
    function findBoundary(root, result, isLeftBoundary, isRightBoundary) {
        
        if(root === null) {
           return;
        }
        
        if(root.left === null && root.right === null) {
           result.push(root.val);
           return; 
        }
            
        if (isLeftBoundary) {
            result.push(root.val);
            findBoundary(root.left,result,root.left!=null,false);
            findBoundary(root.right,result,root.left==null,false);
            return;
        }
        if (!isLeftBoundary && !isRightBoundary){
            findBoundary(root.left,result,false,false);
            findBoundary(root.right,result,false,false);
            return;
        }
        if (isRightBoundary) {
            findBoundary(root.left,result,false,root.right==null);
            findBoundary(root.right,result,false,root.right!=null);
            result.push(root.val);
        }        
    }
    

Log in to reply
 

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