[英]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) 开始并执行以下操作:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.