标签:class == build you traversal [] int strong UI
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
给定一个二叉树的先序遍历和中序遍历,构造出一颗二叉树。
二叉树的遍历分为先序遍历、中序遍历、后序遍历、层序遍历。
而通过先序遍历和中序遍历、中序遍历和后序遍历 是可以还原该二叉树结构的。
1 private int getIndexInInorder(int[] inorder, int val) { 2 for (int i = 0; i < inorder.length; i++) if (val == inorder[i]) return i; 3 return -1; 4 } 5 private TreeNode build(int[] preorder, int[] inorder, int preIndex, 6 int startInIndex, int endInIndex) { 7 if (endInIndex < startInIndex) return null; 8 TreeNode node = new TreeNode(preorder[preIndex]);//先序,第一个节点一定是根节点 9 // the index of current node in inorder 10 int index = getIndexInInorder(inorder,node.val); //获取该节点在中序数组中的位置,进一步结合startInIndex和endInIndex可以获得左右字树的范围 11 int lenL = index - startInIndex; 12 int lenR = endInIndex - startInIndex - lenL; 13 if (lenL > 0) node.left = build(preorder, inorder, preIndex + 1, startInIndex, 14 index - 1); 15 if (lenR > 0) node.right = build(preorder, inorder, preIndex + lenL + 1, 16 index + 1, endInIndex); 17 return node; 18 } 19 20 public TreeNode buildTree(int[] preorder, int[] inorder) { 21 if (preorder == null || preorder.length == 0) return null; 22 if (inorder == null || inorder.length == 0) return null; 23 if (preorder.length != inorder.length) return null; 24 return build(preorder, inorder, 0, 0, inorder.length - 1); 25 }
105. Construct Binary Tree from Preorder and Inorder Traversal
标签:class == build you traversal [] int strong UI
原文地址:http://www.cnblogs.com/wzj4858/p/7677130.html