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; } }
相關文章
相關標籤/搜索