Every type of Recursion Solution is here

Every type of Recursion Solution is here

Recursion in JavaScript is a technique where a function calls itself to solve a problem. It breaks the problem down into smaller subproblems, typically with a base case to stop the recursion. Each recursive call works on a simpler or smaller instance of the original problem. When the base case is met, the recursion stops, and the results are combined or returned.

const tree = ["apple", {left:"apple"},["apple"], {left:{apple:"apple"}}]

let count = 0;

function countNumberOfApples(tree) {

?if (!tree) return count;??

?if (tree === "apple") {

??count += 1;

?}

??if (typeof(tree) == "object") {

???for (let key in tree){?

???countNumberOfApples(tree[key]);

???}

?return count

?}

?if(Array.isArray(tree)){

?for(let i = 0; i<tree.length; i++ ){

??countNumberOfApples(tree[i][`${key}`]);

}}

console.log("count:", count)

?return count;

}

console.log(countNumberOfApples(tree));?

要查看或添加评论,请登录

Muhammad Ali的更多文章

  • Discipline & Consistency

    Discipline & Consistency

    Achieving stability and maintaining motivation for hard work toward your goals involves several key elements: Clear…

  • The Role of Python into Cyber Security

    The Role of Python into Cyber Security

    A Short Description! Python has become a crucial tool in the realms of Red Hat hacking and ethical hacking, offering…

    1 条评论

社区洞察

其他会员也浏览了