当前位置:网站首页>[JS] - [tree] - learning notes

[JS] - [tree] - learning notes

2022-06-24 23:17:00 Interesting learning

Statement : This note is based on the Nuggets brochure , If you want to learn more details , Please move https://juejin.cn/book/6844733800300150797

1 Binary tree

stay JS in , Binary trees use objects to define . Its structure is divided into three parts :
Data fields
Left child node ( The root node of the left subtree ) References to
Right child node ( The root node of the right subtree ) References to  Insert picture description here

  1. Define a binary tree constructor
//  The constructor of a binary tree node 
function TreeNode(val) {
    
    this.val = val;
    this.left = this.right = null;
}
  1. Create a new binary tree node
const node  = new TreeNode(1)

1.1 The first sequence traversal

//  The input parameters of all traversal functions are the root node objects of the tree 
function preorder(root) {
    
   #  Recursive boundary ,root  It's empty 
    if(!root) {
    
        return 
    }
     
    #  Output the current traversal node value 
    console.log(' The node value currently traversed is :', root.val)  
    //  Recursively traverses the left subtree  
    preorder(root.left)  
    //  Recursively traverses the right subtree  
    preorder(root.right)
}

1.2 In the sequence traversal

#  The input parameters of all traversal functions are the root node objects of the tree 
function inorder(root) {
    
    //  Recursive boundary ,root  It's empty 
    if(!root) {
    
        return 
    }
     
    //  Recursively traverses the left subtree  
    inorder(root.left)  
    //  Output the current traversal node value 
    console.log(' The node value currently traversed is :', root.val)  
    //  Recursively traverses the right subtree  
    inorder(root.right)
}

1.3 After the sequence traversal

function postorder(root) {
    
    //  Recursive boundary ,root  It's empty 
    if(!root) {
    
        return 
    }
     
    //  Recursively traverses the left subtree  
    postorder(root.left)  
    //  Recursively traverses the right subtree  
    postorder(root.right)
    //  Output the current traversal node value 
    console.log(' The node value currently traversed is :', root.val)  
}
原网站

版权声明
本文为[Interesting learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241743274111.html