简体   繁体   中英

Recursion in Merge Sort , Quick Sort and traversal of trees

While learing different algorithms (like merge sort , quick sort or Tree traversals) I have observed that there are two recursive calls immediately followed by each other.

I am unable to understand completely.Pls explain in simple terms why do we use two recursive calls? Is this any kind of pattern?

Also are there any algorithms where more than two immediate recursive calls are made?

Merge Sort

m_sort(numbers, temp, left, mid);

m_sort(numbers, temp, mid+1, right);

Tree Traversals

preorder(node.left)

preorder(node.right)

There are two recursive calls because the same function needs to be performed in two different places. In the case of tree traversals starting from the root you want to recursively go down the left and then down the right. The way that function calls work, F calls preorder(node.left) and knows nothing about preorder(node.right) . When it goes into the node.left it is now at B . The same recursive call will be made there all the way until the bottom, at A . When preorder(node.left) returns from A then the code in B calls preorder(node.right) and the recursion will continue.

This isn't so much a pattern as the nature of doing recursive work on many binary structures, where a divide-and-conquer strategy is adapted to split the work into smaller parts, and then recursion is performed on each part seperately until the trivial case is met (such as a node without children as in A , when it returns)

维基百科的预遍历

Source: " Sorted binary tree preorder " by Sorted_binary_tree.svg : Miles derivative work: Pluke ( talk ) - Sorted_binary_tree.svg . Licensed under Public Domain via Wikimedia Commons .

The reason you want to call it twice is that because it splits the problem into half.

For the sorting case, you want to sort the lower half and the upper half. And in the tree case, you want to traverse the left track and the right track. It just happened the number is 2 because you split the domain into half in each recursion. But you can split the problem into how many parts you want, and some problem might even has variable number of parts in each recursion.

An easy way to imagine this, when you stand in a crossroad, you think about how many directions you can go from there, and if you want to visit all of the directions, then you need to call all of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM