Binary tree in order traversal in JavaScriptc

0

Table of Contents

Problem

Given the root of a binary tree, return the inorder traversal of its nodes’ values.

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
   
    let result = new Array();
    let rooot = new Array();
    rooot = root;
    if(root){
         console.log(rooot.val);
         if(root.left == null && root.right == null){
        result.push(root.val);
    } 
    else if(root.left != null || root.right != null){
        result = inordertraversal(root,result);
    }
    }
   
    return result;
    
    
};
function inordertraversal(root,arr){
    
    if(!root){
        return null;
    }
    else{
        inordertraversal(root.left,arr);
        arr.push(root.val);
        inordertraversal(root.right,arr);
    }
    return arr;
}

Leave a Comment

Skip to content