Java对二叉树的操作
生活随笔
收集整理的這篇文章主要介紹了
Java对二叉树的操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
????面試題7:重建二叉樹 題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹,假設輸入的前序遍歷和中序遍歷的結果中都不包含重復的數字。例如:輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6}則重建如圖(a)所示的二叉樹并輸出它的頭節點。二叉樹節點的定義如(b):
? ???????????????????
???? ??????? (a)?? ????
struct BinaryTreeNode {int m_nValue;BinaryTreeNode m_pLeft;BinaryTreeNode m_pRight; };????????????? (b)????????
示例代碼:
public class BinaryTreeNode {public int value; /*結點的值*/BinaryTreeNode leftNode; /*左子樹*/BinaryTreeNode rightNode; /*右子樹*/ } public class BinaryTree {public static void main(String args[]){int[] preSort = {1,2,4,7,3,5,6,8}; /*前序遍歷序列*/int[] inSort = {4,7,2,1,5,3,8,6}; /*中序遍歷序列*/}public static BinaryTreeNode constructCore(int[] preorder,int[] inorder)throws Exception{/*兩個序列不能為空*/if (preorder == null || inorder == null){return null;}/*兩個序列長度要一樣*/if (preorder.length != inorder.length){throw new Exception("長度不一樣,非法的輸入");}BinaryTreeNode root = new BinaryTreeNode();/*前序遍歷的第一個就是根節點*/for (int i = 0;i < inorder.length;i++){if (inorder[i] == preorder[0]){root.value = inorder[i];System.out.println(root.value);/*遍歷左子樹*//**前序遍歷的左子樹是下標從1到i+1(不包括i+1)的數*中序遍歷的左子樹是下標從0到i(不包括i)的數* */root.leftNode = constructCore(Arrays.copyOfRange(preorder,1,i+1),Arrays.copyOfRange(inorder,0,i));root.rightNode = constructCore(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));}}return root;} }總結
以上是生活随笔為你收集整理的Java对二叉树的操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java实现反向输出链表
- 下一篇: java美元兑换,(Java实现) 美元