今天再做求二叉树总结点时,出现了空指针问题,十分差异
期初我是用this来判断这个结点是否为空,之后就报了空指针,但离谱的是我改为用this.left、this.right来判断该姐点是否为空,程序就正常了,但但这两种判断方法都一样怎么就报错了,感到很奇观,this和this.left同样指的是空节点,一个居然会报错
public int getDepth(){
if(this==null) return 0;
int L=this.left.getDepth();
int R=this.right.getDepth();
return L+R+1;
}
全部代码:
public class BinaryTreeDemo {
public static void main(String args[]) {
//先创建一个二叉树对象
BinaryTree binaryTree = new BinaryTree();
// 创建结点
HeroNode root = new HeroNode("宋江");
HeroNode node1 = new HeroNode("张三");
HeroNode node2 = new HeroNode("李四");
HeroNode node3 = new HeroNode("王五");
HeroNode node4 = new HeroNode("麻六");
// 建立结点关系
root.setLeft(node1);
root.setRight(node2);
node1.setLeft(node3);
node1.setRight(node4);
// 确认根结点
binaryTree.setRoot(root);
//输出
System.out.println("前序查找:");
binaryTree.preOrder();
System.out.println("\n中序查找:");
binaryTree.infixOrder();
System.out.println("\n后序查找:");
binaryTree.postOrder();
binaryTree.getDepth();
}
}
//定义BinaryTree 二叉树
class BinaryTree {
HeroNode root;//定义根结点
public void setRoot(HeroNode root) {
this.root = root;
}
//前序遍历
public void preOrder() {
if (this.root == null) {
System.out.println("当前二叉树为空,无法遍历");
} else {
this.root.preOrder();
}
}
//中序遍历
public void infixOrder() {
if (this.root == null) {
System.out.println("当前二叉树为空,无法遍历");
} else {
this.root.infixOrder();
}
}
//后序遍历
public void postOrder() {
if (this.root == null) {
System.out.println("当前二叉树为空,无法遍历");
} else {
this.root.postOrder();
}
}
//获取总结点数
public void getDepth(){
if(this.root==null){
System.out.println("总结点数为0");
}
else{
int deepth=this.root.getDepth();
System.out.println("总结点数为:"+deepth);
}
}
}
//先创建HeroNode结点
class HeroNode {
String data;
HeroNode left;
HeroNode right;
public HeroNode getLeft() {
return left;
}
public HeroNode getRight() {
return right;
}
public void setRight(HeroNode right) {
this.right = right;
}
public void setLeft(HeroNode left) {
this.left = left;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public HeroNode(String data) {
this.data = data;
}
//前序查找方法
public void preOrder() {
//先输出父节点
System.out.print(this.data + ' ');
//递归向左遍历
if (this.left != null) {
this.left.preOrder();
}
//递归向右遍历
if (this.right != null) {
this.right.preOrder();
}
}
// 中序遍历
public void infixOrder() {
//递归向左遍历(先左)
if (this.left != null) {
this.left.infixOrder();
}
//输出节点(后根)
System.out.print(this.data + ' ');
//递归向右遍历(再右)
if (this.right != null) {
this.right.infixOrder();
}
}
// 后序遍历
public void postOrder() {
//递归向左遍历(先左)
if (this.left != null) {
this.left.postOrder();
}
//递归向右遍历(后右)
if (this.right != null) {
this.right.postOrder();
}
//输出节点(再根)
System.out.print(this.data + ' ');
}
public int getDepth(){
if(this==null) return 0;
int L=this.left.getDepth();
int R=this.right.getDepth();
return L+R+1;
}
}