简体   繁体   English

谁能解释二叉树遍历的递归代码?

[英]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.试试 map 把它写出来。 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:现在遍历从根 (5) 开始并执行以下操作:

  • go left to 3 (recursive call #1) go 留给 3(递归调用 #1)
  • go left to 1 (recursive call #2) go 留给 1(递归调用 #2)
  • add 1加 1
  • from 1 go right to 2 (recursive call #3)从 1 go 到 2(递归调用#3)
  • add 2加 2
  • back to 1 (call #3 returns)回到 1(调用 #3 返回)
  • back to 3 (call #2 returns)回到 3(调用 #2 返回)
  • add 3加 3
  • go right to 4 (recursive call #4) go 右转 4(递归调用#4)
  • add 4加 4
  • back to 3 (call #4 returns)回到 3(调用 #4 返回)
  • back to 5 (call #1 returns)回到 5(调用 #1 返回)
  • add 5加 5
  • go right to 7 (recursive call #5) go 对 7(递归调用#5)
  • ... (I'll let you map out the rest) ...(我会让你 map 剩下的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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