LeetCode重建二叉树系列问题总结

二叉树自然的递归特性,使得咱们能够使用递归算法对二叉树进行遍历和重建。以前已经写过LeetCode二叉树的前序、中序、后序遍历(递归实现),那么本文将进行二叉树的重建,通过对比,会发现两者有着许多类似之处。html

准备工做

二叉树节点定义:node

//Definition for a binary tree node.
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }

须要用到数组部分复制的API:算法


LeetCode题解

LeetCode上面关于二叉树重建的问题有:        数组

#
Title
105
106
889
 

 105. Construct Binary Tree from Preorder and Inorder Traversal

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

class Solution { public TreeNode buildTree(int[] pre, int[] in) { if (pre.length == 0) { return null; } System.out.println(pre[0]); TreeNode res = new TreeNode(pre[0]); int index = getIndex(in, pre[0]); res.left = buildTree(Arrays.copyOfRange(pre, 1, index +  1), Arrays.copyOfRange(in, 0, index)); res.right = buildTree(Arrays.copyOfRange(pre, index + 1, pre.length), Arrays.copyOfRange(in, index + 1, in.length)); return res; } public static int getIndex(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { return i; } } return -1; } }

106. Construct Binary Tree from Inorder and Postorder Traversal

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

class Solution { public TreeNode buildTree(int[] in, int[] post) { if (in.length == 0 || post.length == 0) { return null; } if (in.length == 1) { return new TreeNode(in[0]); } TreeNode res = new TreeNode(post[post.length - 1]); int index = getIndex(in, post[post.length - 1]); res.left = buildTree(Arrays.copyOfRange(in, 0, index),  Arrays.copyOfRange(post, 0, index)); res.right = buildTree(Arrays.copyOfRange(in, index + 1, in.length), Arrays.copyOfRange(post, index, post.length -  1)); return res; } public static int getIndex(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { return i; } } return -1; } }

889. Construct Binary Tree from Preorder and Postorder Traversal

Return any binary tree that matches the given preorder and postorder traversals.spa

Values in the traversals pre and post are distinct positive integers.code

class Solution { public TreeNode constructFromPrePost(int[] pre, int[] post) { if (pre.length == 0) { return null; } if (pre.length == 1) { return new TreeNode(pre[0]); } TreeNode res = new TreeNode(pre[0]); int index = getIndex(pre, post[post.length - 2]); res.left = constructFromPrePost(Arrays.copyOfRange(pre,  1, index), Arrays.copyOfRange(post, 0, index - 1)); res.right = constructFromPrePost(Arrays.copyOfRange(pre, index, pre.length), Arrays.copyOfRange(post, index - 1, post.length -  1)); return res; } public static int getIndex(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { return i; } } return -1; } }
相关文章
相关标签/搜索