Construct Binary Tree from Inorder and Postorder Traversal

來源:互聯網
上載者:User

標籤:

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

 Notice

You may assume that duplicates do not exist in the tree.

 Example

Given inorder [1,2,3] and postorder [1,3,2], return a tree:

  2 / 1   3
分析:這是非常典型的遞迴問題,postorder的最後一個是root,在inorder裡面找出root的位置,左邊部分為左子樹,右邊部分為右子樹,稍微麻煩的部分就是確定左子樹和右子樹的starting index。
 1 /** 2  * Definition of TreeNode: 3  * public class TreeNode { 4  *     public int val; 5  *     public TreeNode left, right; 6  *     public TreeNode(int val) { 7  *         this.val = val; 8  *         this.left = this.right = null; 9  *     }10  * }11  */12  13  14 public class Solution {15     /**16      *@param inorder : A list of integers that inorder traversal of a tree17      *@param postorder : A list of integers that postorder traversal of a tree18      *@return : Root of a tree19      */20     public TreeNode buildTree(int[] inorder, int[] postorder) {21         if (inorder == null || postorder == null || postorder.length == 0 || inorder.length != postorder.length) return null;22         23         return buildTree(inorder, 0, postorder, 0, inorder.length);24         25     }26     27     public TreeNode buildTree(int[] inorder, int inStart, int[] postorder, int postStart, int length) {28         if (length <= 0) return null;29         TreeNode root = new TreeNode(postorder[postStart + length - 1]);30 31         int index = findIndex(inorder, root.val);32         root.left = buildTree(inorder, inStart, postorder, postStart, index - inStart);33         root.right = buildTree(inorder, index + 1, postorder, postStart + (index - inStart), length - (index - inStart) - 1);34 35         return root;    36         37     }38 39     public int findIndex(int[] inorder, int val) {40         for (int i = 0; i < inorder.length; i++) {41             if (inorder[i] == val) {42                 return i;43             }44         }45         return -1;46     }47 }

 

  

Construct Binary Tree from Inorder and Postorder 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.