1. 程式人生 > 其它 >二叉樹查詢節點

二叉樹查詢節點

前序中序後序的方式查詢指定的節點

前序查詢思路
1.先判斷當前節點的no是否等於要查詢的
2.如果是相等,則返回當前節點
3.如果不等,則判斷當前節點的左子節點是否為空,如果不為空,則遞迴前序查詢
4.如果左遞迴前序查詢,找到節點,則返回,否則繼續判斷,當前節點的右子節點是否為空,如果
不為空,則繼續向右遞迴前序查詢

中序查詢思路
1.判斷當前節點的左子節點是否為空,如果不為空,則遞迴中序查詢
2.如果找到,則返回,如果沒有找到,就和當前節點比較,如果是則返回當前節點,否則繼續進行右
遞迴的中序查詢
3.如果右遞迴中序查詢,找到就返回,否則返回null

後序查詢思路
1.判斷當前節點的左子節點是否為空,如果不為空,則遞迴後序查詢
2.如果找到就返回,如果沒有找到就判斷當前節點的右子節點是否為空,如果不為空,則右遞迴進行
後序查詢,如果找到就返回
3.和當前節點進行比較,如果是就返回,如果不是就返回null

程式碼實現

HeroNode類中的三個方法

	//前序遍歷查詢
    //如果找到就返回node,如果沒有找到就返回null
    public HeroNode preOrderSearch(int no){
        System.out.println("進入前序遍歷");
        if(this.no==no){
            return this;
        }
        //1.判斷當前節點的左子節點是否為空,如果不為空,則遞迴前序查詢
        //2.如果左遞迴前需查詢找到節點,就返回
        HeroNode resNode=null;
        if (this.left!=null){
            resNode=this.left.preOrderSearch(no);
        }
        if (resNode!=null){//說明左子樹找到
            return resNode;
        }
        //1.判斷當前節點的右子節點是否為空,如果不為空,則遞迴前序查詢
        //2.如果右遞迴前需查詢找到節點,就返回
        if (this.right!=null){
            resNode=this.right.preOrderSearch(no);
        }
        return resNode;

    }

    //中序遍歷查詢
    public HeroNode infixOrderSearch(int no){
        //判斷當前節點的左子節點是否為空,如果不為空,則遞迴中序查詢
        HeroNode resNode=null;
        if (this.left!=null){
            resNode=this.left.infixOrderSearch(no);
        }
        if (resNode!=null){
            return resNode;
        }
        System.out.println("進入中序遍歷查詢");
        //如果左子樹沒有找到,就查詢當前節點
        if (this.no==no){
            return this;
        }
        //否則繼續中序查詢
        if (this.right!=null){
            resNode=this.right.infixOrderSearch(no);
        }
        return resNode;
    }

    //後序遍歷查詢
    public HeroNode postOrderSearch(int no){

        HeroNode resNode=null;
        //判斷當前節點的左子節點是否為空,如果不為空,則遞迴後序查詢
        if (this.left!=null){
            resNode=this.left.postOrderSearch(no);
        }
        if (resNode!=null){
            return resNode;
        }

        //如果左子樹沒有找到就向右子樹遞迴後序查詢
        if (this.right!=null){
            resNode=this.right.postOrderSearch(no);
        }
        if (resNode!=null){
            return resNode;
        }
        System.out.println("進入後序遍歷查詢");
        //如果左右子樹都沒有找到,就比較當前節點是不是
        if (this.no==no){
            return this;
        }
        return null;
    }
    
    
BinaryTree中的三個方法
	//前序遍歷查詢
    public HeroNode preOrderSearch(int no){
        if (root!=null){
            return root.preOrderSearch(no);
        }else {
            return null;
        }
    }

    //中序遍歷查詢
    public HeroNode infixOrderSearch(int no){
        if (root!=null){
            return root.infixOrderSearch(no);
        }else {
            return null;
        }
    }

    //後序遍歷查詢
    public HeroNode postOrderSearch(int no){
        if (root!=null){
            return root.postOrderSearch(no);
        }else {
            return null;
        }
    }