构造二叉树集锦
Posted *平芜尽处是春山*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了构造二叉树集锦相关的知识,希望对你有一定的参考价值。
构造二叉树集锦
105. 从前序与中序遍历序列构造二叉树
class Solution
int index = 0;
public TreeNode buildTree(int[] preorder, int[] inorder)
return buildTreeInternal(preorder,inorder,0,inorder.length);
public TreeNode buildTreeInternal(int[] preOrder,int[] inOrder,int left,int right)
if(left >= right)
return null;
if(index >= preOrder.length)
return null;
TreeNode root = new TreeNode(preOrder[index]);
index++;
int pos = find(inOrder,left,right,root.val);
root.left = buildTreeInternal(preOrder,inOrder,left,pos);
root.right = buildTreeInternal(preOrder,inOrder,pos + 1,right);
return root;
private int find(int[] inOrder,int left,int right,int val)
for(int i = left;i < right;i++)
if(inOrder[i] == val)
return i;
return -1;
运行截图:
106. 从中序与后序遍历序列构造二叉树
class Solution
Map<Integer,Integer> map = new HashMap<> ();
public TreeNode buildTree(int[] inorder, int[] postorder)
int[] preOrder = reverse(inorder,postorder);
return buildTreeInteral(preOrder,inorder,0,inorder.length);
int index = 0;
public TreeNode buildTreeInteral(int[] preOrder,int[] inOrder,int left,int right)
if(left >= right)
return null;
if(index >= preOrder.length)
return null;
TreeNode root = new TreeNode(preOrder[index]);
index++;
int pos = map.get(root.val);
root.right = buildTreeInteral(preOrder,inOrder,pos + 1,right);
root.left = buildTreeInteral(preOrder,inOrder,left,pos);
return root;
private int[] reverse(int[] inorder,int[] postorder)
int[] ret = new int[postorder.length];
for(int i = 0;i < ret.length;i++)
ret[i] = postorder[ret.length - 1 -i];
for(int i = 0;i < inorder.length;i++)
map.put(inorder[i],i);
return ret;
运行截图:
889. 根据前序和后序遍历构造二叉树
class Solution
public TreeNode constructFromPrePost(int[] preorder, int[] postorder)
int length = preorder.length;
TreeNode root = new TreeNode(preorder[0]);
Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
stack.push(root);
int postorderIndex = 0;
for (int i = 1; i < length; i++)
TreeNode prev = stack.peek();
TreeNode curr = new TreeNode(preorder[i]);
if (prev.val != postorder[postorderIndex])
prev.left = curr;
stack.push(curr);
else
while (stack.peek().val == postorder[postorderIndex])
stack.pop();
postorderIndex++;
prev = stack.peek();
prev.right = curr;
stack.push(curr);
return root;
运行截图:
以上是关于构造二叉树集锦的主要内容,如果未能解决你的问题,请参考以下文章