简体   繁体   中英

can anyone Explain recursive code for binary tree traversal?

Inorder traversal for binary trees using recursion.

can anyone explain how these recursion calls working here.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> inorder=new ArrayList<>();
        result(root,inorder);
        return inorder;
    }
    void result(TreeNode root,ArrayList<Integer> inorder){
        if (root==null){
            return ;
        }
        result(root.left,inorder);
        inorder.add(root.val);
        result(root.right,inorder);
    }
}

I was unable to understand how that recursion works.

Try to map it out on paper. It's basically this: for each node you're adding all nodes of the left sub tree to the list, then the node and then all nodes of the right sub tree. If the nodes are ordered so that the left nodes all have a lower value and the right nodes all have a larger value than the node forming the root of a (sub) tree, then the list will be sorted.

I'll help you with an example.

Let's assume the following tree:

         5
     /      \
    3        7
   / \      / \
  1   4    6   8
   \            \  
    2            9

Now traversal starts at the root (5) and does the following:

  • go left to 3 (recursive call #1)
  • go left to 1 (recursive call #2)
  • add 1
  • from 1 go right to 2 (recursive call #3)
  • add 2
  • back to 1 (call #3 returns)
  • back to 3 (call #2 returns)
  • add 3
  • go right to 4 (recursive call #4)
  • add 4
  • back to 3 (call #4 returns)
  • back to 5 (call #1 returns)
  • add 5
  • go right to 7 (recursive call #5)
  • ... (I'll let you map out the rest)

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