構造數組的MaxTree(offer收割)

題目

定義二叉樹的節點以下:java

public class Node{
    public int value;
    public Node left;
    public Node right;
    public Node(int data){
        this.value=data;
    }
}
複製代碼

一個數組的MaxTree定義以下:node

  • 數組必須沒有重複元素。
  • 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);
	}

}
複製代碼
相關文章
相關標籤/搜索