java中关于引用与值传递的问题
public class SearchTree {
TreeNode root =null;
public void insertTree(TreeNode root, int x){
if(root == null){
root = new TreeNode(x);
}
else{
if(x <= root.val){
insertTree(root.left,x);
}
else{
insertTree(root.right,x);
}
}
//preOrder(root);
}
public void preOrder(TreeNode root){
if(root.left == null && root.right == null){
System.out.println(root.val);
}
else if(root.left == null && root.right != null){
System.out.println(root.val);
preOrder(root.right);
}
else if(root.left != null&& root.right == null){
preOrder(root.left);
System.out.println(root.val);
}
else {
preOrder(root.left);
System.out.println(root.val);
preOrder(root.right);
}
}
public static void main(String[] args) {
SearchTree st = new SearchTree();
int a[]={5,2,3,5,7,8};
//TreeNode root = null ;
for(int i = 0; i < a.length; i++){
st.insertTree(st.root, a[i]);
}
st.preOrder(st.root);
}
}
class SearchTree {
TreeNode root=null;
public void insertTree(TreeNode node, int x) {
if (node==null) {
root=new TreeNode(x);
} else {
if (x<=node.val) {
if (node.left==null) {
node.left=new TreeNode(x);
} else {
insertTree(node.left,x);
}
} else {
if (node.right==null) {
node.right=new TreeNode(x);
} else {
insertTree(node.right,x);
}
}
}
preOrder(root);
}
public void preOrder(TreeNode node) {
if (node==null) {
System.out.println("null");
}
if (node.left==null&&node.right==null) {
System.out.println(node.val);
} else if (node.left==null&&node.right!=null) {
System.out.println(node.val);
preOrder(node.right);
} else if (node.left!=null&&node.right==null) {
preOrder(node.left);
System.out.println(node.val);
} else {
preOrder(node.left);
System.out.println(node.val);
preOrder(node.right);
}
}
public static void main(String[] args) {
SearchTree st=new SearchTree();
int a[]={5,2,3,5,7,8};
//TreeNode root = null ;
for (int i=0; i<a.length; i++) {
st.insertTree(st.root,a[i]);
}
st.preOrder(st.root);
System.out.println(st.root);
}
}