我有一种方法来展平二进制搜索树.我有两种方法:
•使用变量并传递它
import java.util.*;
public class BST {
private Node root;
private class Node {
private int val; // associated data
private Node left, right; // left and right subtree
public Node(int val) {
this.val = val;
}
}
public ArrayList flattenTree(){
ArrayList list = new ArrayList<>();
flattenTree(root, list);
return list;
}
public void flattenTree(Node node, ArrayList list)
{
if (node == null)
return;
flattenTree(node.left, list);
list.add(node.val);
flattenTree(node.right, list);
}
public static void main(String[] args) {
BST bst = new BST();
bst.add(5);
bst.add(1);
bst.add(0);
bst.add(3);
System.out.println(bst.flattenTree());
}
}
•使用类变量:
import java.util.*;
public class BST {
private Node root;
ArrayList list = new ArrayList<>();
private class Node {
private int val; // associated data
private Node left, right; // left and right subtree
public Node(int val) {
this.val = val;
}
}
public ArrayList flattenTree(){
flattenTree(root);
return list;
}
public void flattenTree(Node node)
{
if (node == null)
return;
flattenTree(node.left);
list.add(node.val);
flattenTree(node.right);
}
public static void main(String[] args) {
BST bst = new BST();
bst.add(5);
bst.add(3);
bst.add(1);
bst.add(0);
bst.add(3);
bst.add(3);
bst.printInorder();
System.out.println(bst.flattenTree());
}
}
在这两种情况下,我得到:
sgupta$java BST
[0, 1, 3, 5]
我是java(高中)的初学者,并想知道每种方法的优点和缺点是什么.
我唯一能想到的是,方法#2的代码不那么杂乱,不必通过列表.