I have a way to smooth a binary search tree. I have two approaches to this:
• Using a variable and passing it around
import java.util.*;
public class BST {
private Node root;
private class Node {
private int val;
private Node left, right;
public Node(int val) {
this.val = val;
}
}
public ArrayList<Integer> flattenTree(){
ArrayList<Integer> list = new ArrayList<>();
flattenTree(root, list);
return list;
}
public void flattenTree(Node node, ArrayList<Integer> 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());
}
}
• Using a class variable:
import java.util.*;
public class BST {
private Node root;
ArrayList<Integer> list = new ArrayList<>();
private class Node {
private int val;
private Node left, right;
public Node(int val) {
this.val = val;
}
}
public ArrayList<Integer> 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());
}
}
In both cases, I get:
sgupta$ java BST
[0, 1, 3, 5]
I am new to java (high school) and wondering what are the pros and cons of each approach.
The only thing I can think of is that approach # 2 has less dirty code since it doesn't need to skip the list.
source
share