题目:给定一个二叉树的后序遍历数组arr[],生成二叉树
解题思路:根据搜索二叉树的性质,数组的最后一位arr[end]是二叉树的根,而且数组的左部分比arr[end]小,是根节点的左子数,数字的右部分比arr[end]大,是数组的右子数。
Example:
树的形状如上图,后序遍历为:1 3 2 6 8 7 5
arr[end] = 5;
左部分(左子树):{1,3,2}
右部分(右子树):{6,8,7}
package cn.edu.algorithm.prototype; /** * 根据后序遍历构造二叉树 */ public class Main { public static void main(String[] args) { int[] arr = {1, 3, 2, 6, 8, 7, 5}; TreeNode root = postToBST(arr, 0, arr.length - 1); inOrder(root); } public static void inOrder(TreeNode node) { if (node != null) { inOrder(node.left); System.out.println(node.value); inOrder(node.right); } } public static TreeNode postToBST(int[] arr, int start, int end) { if (start > end) return null; TreeNode node = new TreeNode(arr[end]); int less = -1; int more = end; for (int i = start; i < end; i++) { if (arr[end] > arr[i]) { less = i; } else { more = more == end ? i : more; } } node.left = postToBST(arr, start, less); node.right = postToBST(arr, more, end - 1); return node; } } class TreeNode { protected int value; protected TreeNode left; protected TreeNode right; public TreeNode(int value) { this.value = value; } }
时间: 2024-10-04 09:27:39