Created
April 21, 2018 19:31
-
-
Save mhewedy/ce5abb57abb88bd64a01aa58e7e7e960 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class TreeHeight { | |
| static class Node { | |
| char data; | |
| Node left, right; | |
| Node(char data) { | |
| this.data = data; | |
| } | |
| Node(char data, Node left, Node right) { | |
| this.data = data; | |
| this.left = left; | |
| this.right = right; | |
| } | |
| @Override | |
| public String toString() { | |
| return String.valueOf(data); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| Node f = new Node('f'); | |
| Node g = new Node('g'); | |
| Node h = new Node('h'); | |
| Node d = new Node('d', f, g); | |
| Node e = new Node('e', null, h); | |
| Node c = new Node('c', d, e); | |
| Node b = new Node('b'); | |
| Node a = new Node('a', b, c); | |
| System.out.println(nodeHeight(a)); | |
| } | |
| static int nodeHeight(Node root) { | |
| if (root == null) { | |
| return 0; | |
| } else { | |
| int leftHeight = nodeHeight(root.left); | |
| int rightHeight = nodeHeight(root.right); | |
| return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight); | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment