题目
定义二叉树的节点如下:
public class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value=data;
}
}
复制代码
一个数组的MaxTree定义如下:
- 数组必须没有重复元素。
- MaxTree是一棵二叉树,数组的每一个值对应一个二叉树节点。
- 包括MaxTree树在内且在其中的每一棵子树上,值最大的节点都是树的头。
给定一个没有重复元素的数组arr,写出生成这个数组的MaxTree的函数,要求如果数组的长度为N,则时间复杂度为O(N)、额外空间复杂度为O(N)。
代码
package com.iqiyi;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class Code1_8 {
public static Node getMaxTree(int[] arr) {
Node[] nodes = new Node[arr.length];
for (int i = 0; i < arr.length; i++) {
nodes[i] = new Node(arr[i]);
}
Map<Node, Node> map1 = new HashMap<Node, Node>();
Stack<Node> stack1 = new Stack<Node>();
for (int i = 0; i < arr.length; i++) {
while (!stack1.isEmpty() && stack1.peek().value < nodes[i].value)
stack1.pop();
if (stack1.isEmpty())
map1.put(nodes[i], null);
else
map1.put(nodes[i], stack1.peek());
stack1.push(nodes[i]);
}
Map<Node, Node> map2 = new HashMap<Node, Node>();
Stack<Node> stack2 = new Stack<Node>();
for (int i = arr.length - 1; i >= 0; i--) {
while (!stack2.isEmpty() && stack2.peek().value < nodes[i].value)
stack2.pop();
if (stack2.isEmpty())
map2.put(nodes[i], null);
else
map2.put(nodes[i], stack2.peek());
stack2.push(nodes[i]);
}
Map<Node, Node> map3 = new HashMap<Node, Node>();
Node root = null;
for (int i = 0; i < arr.length; i++) {
Node root1 = map1.get(nodes[i]);
Node root2 = map2.get(nodes[i]);
if (root1 == null && root2 == null)
root = nodes[i];
else if (root1 == null)
map3.put(nodes[i], root2);
else if (root2 == null)
map3.put(nodes[i], root1);
else if (root1.value < root2.value)
map3.put(nodes[i], root1);
else
map3.put(nodes[i], root2);
}
for (int i = 0; i < arr.length; i++) {
if (nodes[i] == root)
continue;
else {
Node node = map3.get(nodes[i]);
if (node.left == null)
node.left = nodes[i];
else
node.right = nodes[i];
}
}
return root;
}
public static class Node {
int value;
Node left;
Node right;
public Node(int data) {
value = data;
}
}
public static void main(String[] args) {
int[] arr=new int[]{3,4,5,1,2};
getMaxTree(arr);
}
}
复制代码