简体   繁体   English

递归期间的字符串参数

[英]String parameter during recursion

I want to understand functionality of following recursive code which basically print paths of a binary tree. 我想了解遵循递归代码的功能,这些功能基本上可以打印二叉树的路径。

//Node has int val; Node left; Node right;
public List<String> printPaths(Node root) {
    List<String> paths = new ArrayList<String>();
    printPaths(root, paths, Integer.toString(root.val)); //root is not null
    return paths;
}

public void printPaths(Node root, List<String> paths, String onePath) {
    if(root.left == null && root.right == null) {
        paths.add(onePath);
    }
    if (root.left != null) {
        printPaths(root.left, paths, onePath + Integer.toString(root.left.val));
    }
    if (root.right != null) {
        printPaths(root.left, paths, onePath + Integer.toString(root.right.val));
    }
}

Now this prints proper path values, but I don't understand that since I update onePath & don't reset it how the value gets reset to root.val for each separate path? 现在这将打印正确的路径值,但是我不明白,因为我更新了onePath且不重置它,因此如何将每个单独路径的值重置为root.val? How is the onePath value getting reset to binary tree's root value for every tree path even after I append "->" + val for the previous path? 即使我为前一个路径附加“->” + val之后,onePath值如何重置为每个树路径的二叉树根值?

A String is immutable, and concatenating two Strings with the + operator creates a new String instance. 一个String是不可变的,将两个String与+运算符连接在一起将创建一个新的String实例。 The original String instances that were concatenated remain unchanged. 串联的原始String实例保持不变。

Therefore, each recursive method call has its own onePath local variable on the call stack, which refers to a different String instance. 因此,每个递归方法调用在调用堆栈上都有其自己的onePath局部变量,该变量引用不同的String实例。

When a call to printPaths(..,..,"something" + "someNumber") returns, the local onePath variable (on the stack frame of that method call) that contained somethingsomeNumber can be garbage collected, and the onePath variable that refers to the String "something" is in the current stack frame. 当返回对printPaths(..,..,"something" + "someNumber")调用时,可以垃圾回收包含somethingsomeNumber的本地onePath变量(在该方法调用的堆栈框架上),并且引用该变量的onePath变量String "something"到当前堆栈帧中。

The only thing that changes is the current stack frame. 唯一更改的是当前堆栈帧。

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

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