Write a code that returns the deepest node in a binary tree. If the tree is complete, having two same depth of node, return the rightmost node.
Utilisateur anonyme
//Last item in Breadth first search class Node { int data; Node left; Node right; Node(int d) { data = d; } @Override public String toString() { return "" + data; } } public class Tree { Node root; public static void main(String[] args) { Tree t = new Tree(); t.root = new Node(5); t.root.left = new Node(10); t.root.right = new Node(20); t.root.left.left = new Node(15); t.root.right.right = new Node(19); System.out.println(t.deepestNode().data); } public Node deepestNode() { if (root == null) { return null; } ArrayList nodes = new ArrayList(); nodes.add(root); Node deepest = null; while (!nodes.isEmpty()) { deepest = nodes.get(0); nodes.remove(0); if (deepest.left != null) { nodes.add(deepest.left); } if (deepest.right != null) { nodes.add(deepest.right); } } return deepest; } }