Application examples of recursion in JavaScript

Recursion

Necessary conditions apply: Describe the process of ① ② has included its own conditions for a clear end recursion.

The main idea: When every call yourself, use the same method to solve the problem, but the parameters of the call is different every time (regular changes), use a termination process (end recursion) conditions, when this condition is satisfied, the disease can get direct solution to terminate the recursion.

Example 1:

Given two binary tree, write a function to check whether they are identical.

If the two are identical in structure tree, and the nodes have the same value, they are considered identical.

Example 1:

Input:

Input: 11
     / \ / \
     2323

[1,2,3], [1,2,3]

Output: true

Example 2:

Input: 11
     / \
     22

[1,2], [1,null,2]

Output: false (Source: leetcode.com)

var isSameTree = function(p, q) {
  if (p == null && q == null)
    return true
  if ((p == null && q != null) || (p != null && q == null))
    return false;
  return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
};

 

Example 2:

We comply with the following attributes of an array called A mountain: A.length> = 3

    (Source: leetcode.com)

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/keang001/p/11551004.html