Created
          August 29, 2018 04:29 
        
      - 
      
 - 
        
Save samcorcos/66d26563f021df117b1b3db1d42e8f36 to your computer and use it in GitHub Desktop.  
    Depth-first Search Javascript
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | const tree = { | |
| id: "1", | |
| children: [ | |
| {id: "2", children: [ | |
| {id: "4", children: [ | |
| {id: "7", children: []} | |
| ]}, | |
| {id: "6", children: []}, | |
| ]}, | |
| {id: "3", children: [ | |
| {id: "5", children: []}, | |
| ]}, | |
| ] | |
| } | |
| // takes in a tree and truncates to a max depth | |
| const dfs = (node, id) => { | |
| if (node.id === id) return true | |
| for (let i = 0; i < node.children.length; i++) { | |
| let found = dfs(node.children[i], id) | |
| if (found) return true | |
| } | |
| return false | |
| } | |
| console.log(dfs(tree, "7")) // => true | |
| console.log(dfs(tree, "5")) // => true | |
| console.log(dfs(tree, "100")) // => false | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment