Construct Binary Tree from Preorder and Inorder Traversal

來源:互聯網
上載者:User

標籤:

Given preorder and inorder traversal of a tree, construct the binary tree.

這道題是要根據先序遍曆和中序遍曆構造出一棵二叉樹,這道題和上一題是一樣的。上一題不過是通過後序遍曆和中序遍曆構造一棵二叉樹。

只要將代碼稍稍修改即可

 1 public class Solution { 2     public TreeNode buildTree(int[] preorder, int[] inorder) { 3         TreeNode root; 4         if(preorder.length == 0) 5             return null; 6         return createTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1); 7  8     } 9     private TreeNode createTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart ,int inEnd){10         if(inStart > inEnd)11             return null;12         int value_root = preorder[preStart];                    //根據先序遍曆第一個元素為根節點,找出根節點的值13         int index = 0;                                            //根節點在中序遍曆中的索引值14         for(int i = inStart; i <= inEnd; i++){                    //尋找根節點在中序遍曆中的索引值15             if(value_root == inorder[i]){16                 index = i;17                 break;18             }19         }//for20         int length_leftTree = index - inStart;                    //左子樹的長度21         TreeNode root_left = createTree(preorder, inorder, preStart + 1, preStart + length_leftTree, inStart, index - 1);22         TreeNode root_right = createTree(preorder, inorder, preStart + length_leftTree + 1, preEnd, index + 1, inEnd);23         24         TreeNode root = new TreeNode(value_root);25         root.left = root_left;26         root.right = root_right;27         28         return root;29     }30 }

 

Construct Binary Tree from Preorder and Inorder Traversal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.