Categories
General

Number of Visible Nodes Facebook

There is a binary tree with N nodes. You are viewing the tree from its left side and can see only the leftmost nodes at each level. Return the number of visible nodes.Note: You can see only the leftmost nodes, but that doesn’t mean they have to be left nodes. The leftmost node at a level could be a right node.Signature int visibleNodes(Node root) {Input The root node of a tree, where the number of nodes is between 1 and 1000, and the value of each node is between 0 and 1,000,000,000Output An int representing the number of visible nodes.Example

            8  <------ root
           / \
         3    10
        / \     \
       1   6     14
          / \    /
         4   7  13            

output = 4

<?php

// Add any extra import statements you may need here


class TreeNode{
  public $val;
  public $left;
  public $right;
  public function __construct($val=0) {
    $this->val = $val;
    $this->left = NULL;
    $this->right = NULL;
  }
}

// Add any helper functions you may need here


function visibleNodes($root) {
        $result = [];
        
        $numberVisibleNode = 1;
 
        dfs($root, $result, $numberVisibleNode);
       
        return  max($result);;
    }
    
     function dfs(TreeNode $currentNode, array &$result,$numberVisibleNode )  {
        if(($currentNode->left === null)  && ($currentNode->right === null)) {
                   
           // var_dump($currentNode->val.' '.$numberVisibleNode);
            $result[$currentNode->val] = $numberVisibleNode;
            return ;
        }
        
        if($currentNode->left != null) {
          //  var_dump('leftside '.$currentNode->val.' '.$numberVisibleNode);
            $numberVisibleNodeLeft = $numberVisibleNode;
            $numberVisibleNodeLeft++; #2
            dfs($currentNode->left, $result, $numberVisibleNodeLeft);
        }
        
        if(($currentNode->right !== null)) {
           // var_dump('righttside '.$currentNode->val.' '.$numberVisibleNode);
            $numberVisibleNodeRight = $numberVisibleNode;
            $numberVisibleNodeRight++;#5,
            dfs($currentNode->right, $result, $numberVisibleNodeRight);
        }
    }

Leave a Reply