106 构造树没做出来

This commit is contained in:
whai 2024-01-25 22:33:53 +08:00
parent ca386eaae0
commit 3c1d53ac10
2 changed files with 58 additions and 1 deletions

View File

@ -0,0 +1,55 @@
package cn.whaifree.leetCode.Tree;
import cn.whaifree.leetCode.model.TreeNode;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/1/25 21:29
* @注释
*/
public class LeetCode106 {
@Test
public void test() {
TreeNode treeNode = TreeNode.constructTree(new Integer[]{3,9,20,null,null,15,7});
// 9 3 20 7 15
// 20 3 7 9 15
// 20 7 3 15 9
new Solution().buildTree(new int[]{9,3,15,20,7}, new int[]{9,15,7,20,3}).printTree();
}
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length == 0) {
return null;
}
return circle(inorder, postorder, 0, inorder.length - 1, postorder.length - 1);
}
public TreeNode circle(
int[] inorder,
int[] postorder,
int inorderStart,
int inorderEnd,
int poster
) {
if (poster < 0 || inorderStart > inorderEnd) {
return null;
}
int lastValue = postorder[poster];
// 中序的指针左边为左树右边为右树
int index = 0;
while (inorder[index] != lastValue) {
index++;
}
TreeNode root = new TreeNode(lastValue);
root.right = circle(inorder, postorder, index + 1, inorderEnd, index+inorderEnd-2);
root.left = circle(inorder, postorder, inorderStart, index - 1,inorderStart+index-1 );
return root;
}
}
}

View File

@ -160,6 +160,7 @@ public class TreeNode {
while (index < length) {
index++;
if (index >= length) {
root.printTree();
return root;
}
currNode = nodeQueue.poll();
@ -170,6 +171,7 @@ public class TreeNode {
}
index++;
if (index >= length) {
root.printTree();
return root;
}
Integer rightChild = array[index];
@ -178,7 +180,7 @@ public class TreeNode {
nodeQueue.offer(currNode.right);
}
}
root.printTree();
return root;
}