1.在二叉树中查找元素值为x的节点的操作
1 package com.neusoft.Tree; 2 3 import java.awt.image.RescaleOp; 4 5 /** 6 * @author zhao-chj 7 * 完成在二叉树中查找元素值为x的节点的操作 8 * 在二叉树中查找数据元素的操作要求: 9 * 在以T为根节点的二叉树中查找数据元素为x的节点 10 * 如果找到则返回该元素,否则返回空值 11 */ 12 public class Example1 { 13 //采用先跟遍历的方式对二叉树进行比较 14 public BiTreeNode searchNode(BiTreeNode T,Object x){ 15 if (T!=null) { 16 if (T.data.equals(x)) { 17 return T; 18 }else { 19 //查找左子树 20 BiTreeNode lresult=searchNode(T.lchild, x); 21 //查找右子树 22 BiTreeNode rchildresult=searchNode(T.rchild, x); 23 return lresult !=null?lresult:rchildresult; 24 //如果在左子树中,则返回值为x的元素,否则在右子树查找并返回结果 25 } 26 } 27 return null; 28 } 29 public static void main(String[] args) { 30 BiTree biTree=new BiTreeCreate().createBitree(); 31 BiTreeNode root=biTree.getRoot();//取得根节点元素 32 //Debug 33 Example1 example1 = new Example1(); 34 if (example1.searchNode(root, 'B')!=null) { 35 System.out.println("树中包含指定元素的节点" 36 +example1.searchNode(root, 'B').data); 37 }else { 38 System.out.println("树中不包含指定元素的值~"); 39 } 40 } 41 42 }
点击可复制代码
1 package com.neusoft.Tree; 2 3 import java.awt.image.RescaleOp; 4 5 /** 6 * @author zhao-chj 7 * 完成在二叉树中查找元素值为x的节点的操作 8 * 在二叉树中查找数据元素的操作要求: 9 * 在以T为根节点的二叉树中查找数据元素为x的节点 10 * 如果找到则返回该元素,否则返回空值 11 */ 12 public class Example1 { 13 //采用先跟遍历的方式对二叉树进行比较 14 public BiTreeNode searchNode(BiTreeNode T,Object x){ 15 if (T!=null) { 16 if (T.data.equals(x)) { 17 return T; 18 }else { 19 //查找左子树 20 BiTreeNode lresult=searchNode(T.lchild, x); 21 //查找右子树 22 BiTreeNode rchildresult=searchNode(T.rchild, x); 23 return lresult !=null?lresult:rchildresult; 24 //如果在左子树中,则返回值为x的元素,否则在右子树查找并返回结果 25 } 26 } 27 return null; 28 } 29 public static void main(String[] args) { 30 BiTree biTree=new BiTreeCreate().createBitree(); 31 BiTreeNode root=biTree.getRoot();//取得根节点元素 32 //Debug 33 Example1 example1 = new Example1(); 34 if (example1.searchNode(root, 'B')!=null) { 35 System.out.println("树中包含指定元素的节点" 36 +example1.searchNode(root, 'B').data); 37 }else { 38 System.out.println("树中不包含指定元素的值~"); 39 } 40 } 41 42 }