JavaScript recursive solutions


  • 0
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var boundaryOfBinaryTree = function(root) {
        // --------------------------
        //  Helpers
        // --------------------------
        var isLeaf = function(node) {
            return node && !node.left && !node.right;
        };
    
        var printLeftBoundary = function(node) {
            if (!node || isLeaf(node)) return;
            
            result.push(node.val);
            
            if (node.left) {
                printLeftBoundary(node.left);
            } else {
                printLeftBoundary(node.right);
            }
        };
        
        var printRightBoundary = function(node) {
            if (!node || isLeaf(node)) {
                return;
            }
            
            if (node.right) {
                printRightBoundary(node.right);
            } else {
                printRightBoundary(node.left);
            }
            
            result.push(node.val);
        };
        
        var printLeaves = function(node) {
            if (!node) {
                return;
            }
            
            if (isLeaf(node)) {
                result.push(node.val);
            }
            
            printLeaves(node.left);
            printLeaves(node.right);
        };
        
        // --------------------------
        //  Main
        // --------------------------
        if (!root) {
            return [];
        }
        
        var result = [root.val];
        
        printLeftBoundary(root.left);
        printLeaves(root.left);
        printLeaves(root.right);
        printRightBoundary(root.right);
        
        return result;
    };
    

Log in to reply
 

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