Pergunta de entrevista da empresa Google

Find the deepest node in a binary tree; Build a tree out of given edges; etc

Respostas da entrevista

Sigiloso

12 de abr. de 2015

import java.util.LinkedList; import java.util.Queue; public class DeepestNode { public static TNode deepestNode(BST b) { TNode root=b.root; if(root==null) return null; Queue nodes=new LinkedList(); Queue count=new LinkedList(); nodes.add(root); TNode cur=null; while(!nodes.isEmpty()) { cur=nodes.poll(); if(cur.left!=null) nodes.add(cur.left); if(cur.right!=null) nodes.add(cur.right); } return cur; } public static void main(String[] args) { BST b=new BST(); b.insert(6); b.insert(2); b.insert(10); b.insert(-1); b.insert(3); b.insert(8); b.insert(17); b.insert(15);b.insert(13); b.insert(16); TNode op=deepestNode(b); if(op!=null) System.out.println(op.data); } } public class TNode{ int data; TNode left; TNode right; TNode() { } TNode(int d) { data=d; left=null; right=null; } }

Sigiloso

7 de ago. de 2015

int max = 0; Node answer = null; Node previous = null; public Node deepestNode(Node node) { maxDepth(node, 0); return answer; } private void maxDepth(Node node, int depth) { if (node == null) { if (depth > max) { max = depth - 1; answer = previous; } } previous = node; return Math.max(maxDepth(node.left, depth + 1), maxDepth(node.right, depth + 1)); }