二叉樹的前序,中序,後序查詢

2021-10-02 23:26:58 字數 1350 閱讀 8521

主要還是對遞迴的理解,查詢和遍歷都是用了兩個遞迴,遞迴的查詢總是先查詢乙個節點的最左邊節點。每次遞迴都會列印左右兩邊的節點。其實有點像while迴圈,但是乙個遞迴的方法中還包含著另乙個遞迴。按照順序執行

package a;

public class binarytreedemo

}}class binarytree

public hero prefind(int no)

// if (root.left != null)

}else

}public hero infixfind(int no) else

}public hero suffixfind(int no) else

}public void pre()else

}public void infix()else

}public void sufix()else

}}class hero

@override

public string tostring() ';

}public hero prefind(int no)

hero res = null;

if (this.left != null)

if (res != null)

if (this.right != null)

return res;

}public hero infixfind(int no)

if (res != null)

if (this.no == no)

if (this.right != null)

return res;

}public hero suffixfind(int no)

if (res != null)

if (this.right != null)

if (res != null)

if (this.no == no)

return res;

}//前序遍歷。這次我們將方法寫在節點中。也就是省去了對自身判斷為null的步驟。方便遞迴

public void pre()

if (this.right != null)

}public void infix()

system.out.println(this);

if (this.right != null)

}public void suffix()

if (this.right != null)

system.out.println(this);

}}

二叉樹遍歷(前序,中序,後序

二叉樹的遍歷有三種方式,如下 1 前序遍歷 dlr 首先訪問根結點,然後遍歷左子樹,最後遍歷右子樹。簡記根 左 右。2 中序遍歷 ldr 首先遍歷左子樹,然後訪問根結點,最後遍歷右子樹。簡記左 根 右。3 後序遍歷 lrd 首先遍歷左子樹,然後遍歷右子樹,最後訪問根結點。簡記左 右 根。例1 如上圖...

前序中序出後序 二叉樹

描述 輸入一棵二叉樹的先序和中序遍歷序列,輸出其後序遍歷序列。輸入輸入檔案為tree.in,共兩行,第一行乙個字串,表示樹的先序遍歷,第二行乙個字串,表示樹的中序遍歷。樹的結點一律用小寫字母表示。輸出輸出檔案為tree.out,僅一行,表示樹的後序遍歷序列。樣例輸入 abdec dbeac 樣例輸出...

二叉樹的前序查詢 中序查詢和後序查詢

使用前序,中序,後序的方式來查詢指定的結點 前序查詢思路 1.先判斷當前結點的no是否等於要查詢的 2.如果是相等,則返回當前結點 3.如果不等,則判斷當前結點的左子節點是否為空,如果不為空,則遞迴前序查詢 4.如果左遞迴前序查詢,找到結點,則返回,否繼續判斷,當前的結點的右子節點是否為空,如果不空...