층차+중차순으로 두 갈래 트리 만들기
4934 단어 학습 노트
Input: Two arrays that represent Inorder
and level order traversals of a
Binary Tree
in[] = {4, 8, 10, 12, 14, 20, 22};
level[] = {20, 8, 22, 4, 12, 10, 14};
Output: Construct the tree represented
by the two arrays.
For the above two arrays, the
constructed tree is shown in
the diagram on right side
Let us consider the above example. in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14};
In a Levelorder sequence, the first element is the root of the tree. So we know ’20’ is root for given sequences. By searching ’20’ in Inorder sequence, we can find out all elements on left side of ‘20’ are in left subtree and elements on right are in right subtree. So we know below structure now.
20
/ \
/ \
{4,8,10,12,14} {22}
Let us call {4,8,10,12,14} as left subarray in Inorder traversal and {22} as right subarray in Inorder traversal. In level order traversal, keys of left and right subtrees are not consecutive. So we extract all nodes from level order traversal which are in left subarray of Inorder traversal. To construct the left subtree of root, we recur for the extracted elements from level order traversal and left subarray of inorder traversal. In the above example, we recur for following two arrays.
// Recur for following arrays to construct the left subtree
In[] = {4, 8, 10, 12, 14}
level[] = {8, 4, 12, 10, 14}
Similarly, we recur for following two arrays and construct the right subtree.
// Recur for following arrays to construct the right subtree
In[] = {22}
level[] = {22}
Following is the implementation of the above approach.
// Java program to construct a tree from level order and
// and inorder traversal
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
public void setLeft(Node left)
{
this.left = left;
}
public void setRight(Node right)
{
this.right = right;
}
}
class Tree
{
Node root;
Node buildTree(int in[], int level[])
{
Node startnode = null;
return constructTree(startnode, level, in, 0, in.length - 1);
}
Node constructTree(Node startNode, int[] levelOrder, int[] inOrder,
int inStart, int inEnd)
{
// if start index is more than end index
if (inStart > inEnd)
return null;
if (inStart == inEnd)
return new Node(inOrder[inStart]);
boolean found = false;
int index = 0;
// it represents the index in inOrder array of element that
// appear first in levelOrder array.
for (int i = 0; i < levelOrder.length - 1; i++)
{
int data = levelOrder[i];
for (int j = inStart; j < inEnd; j++)
{
if (data == inOrder[j])
{
startNode = new Node(data);
index = j;
found = true;
break;
}
}
if (found == true)
break;
}
//elements present before index are part of left child of startNode.
//elements present after index are part of right child of startNode.
startNode.setLeft(constructTree(startNode, levelOrder, inOrder,
inStart, index - 1));
startNode.setRight(constructTree(startNode, levelOrder, inOrder,
index + 1, inEnd));
return startNode;
}
/* Utility function to print inorder traversal of binary tree */
void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
// Driver program to test the above functions
public static void main(String args[])
{
Tree tree = new Tree();
int in[] = new int[]{4, 8, 10, 12, 14, 20, 22};
int level[] = new int[]{20, 8, 22, 4, 12, 10, 14};
int n = in.length;
Node node = tree.buildTree(in, level);
/* Let us test the built tree by printing Inorder traversal */
System.out.print("Inorder traversal of the constructed tree is ");
tree.printInorder(node);
}
}
//This code has been contributed by Mayank Jaiswal Output:
Inorder traversal of the constructed tree is
4 8 10 12 14 20 22
https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
STL 학습노트(6) 함수 객체모방 함수는 모두pass-by-value이다 함수 대상은 값에 따라 전달되고 값에 따라 되돌아오기 때문에 함수 대상은 가능한 한 작아야 한다(대상 복사 비용이 크다) 함수 f와 대상 x, x 대상에서 f를 호출하면:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.