Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 16, 2017 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/0aad7dc3f5021340b651805bcc786cdd to your computer and use it in GitHub Desktop.
Save jianminchen/0aad7dc3f5021340b651805bcc786cdd to your computer and use it in GitHub Desktop.
Tree amplitude - study code
import java.util.*;
class TreeNode
{
public TreeNode left, right;
public int val;
public TreeNode(String val)
{
this.val = Integer.parseInt(val);
}
}
public class Solution {
public static TreeNode buildTree(String[] input)
{
int index = 0;
TreeNode root = new TreeNode(input[index++]);
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(index < input.length)
{
int size = queue.size();
for(int i = 0; i< size; i++)
{
TreeNode t = queue.poll();
if(index >= input.length) return root;
if(!input[index].equals("*"))
{
t.left = new TreeNode(input[index]);
queue.offer(t.left);
}
index++;
if(index >= input.length) return root;
if(!input[index].equals("*"))
{
t.right = new TreeNode(input[index]);
queue.offer(t.right);
}
index++;
if(index >= input.length) return root;
}
}
return root;
}
public static int amplitude(TreeNode root)
{
if(root == null) return 0;
return DFS(root, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
private static int DFS(TreeNode root, int min, int max)
{
if(root == null) return max - min;
if(root.val < min) min = root.val;
if(root.val > max) max = root.val;
return Math.max(DFS(root.left, min, max), DFS(root.right, min, max));
}
public static void main(String[] args)
{
String[] input = {"5", "-8", "9", "-12", "2", "8", "4", "*", "*", "*", "*", "2", "*", "5"};
TreeNode root = buildTree(input);
System.out.println(amplitude(root));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment