본문 바로가기

리트코드/easy

[리트코드] 94. Binary Tree Inorder Traversal - js

반응형

1. 문제

https://leetcode.com/problems/binary-tree-inorder-traversal/description/

 

Binary Tree Inorder Traversal - LeetCode

Can you solve this real interview question? Binary Tree Inorder Traversal - Given the root of a binary tree, return the inorder traversal of its nodes' values.   Example 1: [https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg] Input: root = [1,nu

leetcode.com

2. 코드

/**
 * 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 tree = [];
    // 재귀를 통해 왼 -> 부모 -> 오 노드 순으로 배열에 노드 value push
    const inorder = (root) => {
        if(!root) return;
        
        inorder(root.left);
        tree.push(root.val);
        inorder(root.right);
    }

    inorder(root);

    return tree;
};

 

풀이 참고)

https://leetcode.com/problems/binary-tree-inorder-traversal/solutions/2967362/javascript-recursive-and-iterative-explained/

 

JavaScript - Recursive and Iterative Explained - Binary Tree Inorder Traversal - LeetCode

View Martze's solution of Binary Tree Inorder Traversal on LeetCode, the world's largest programming community.

leetcode.com

 

반응형