Exemple #1
0
        Tree(Tree left, Tree right, int? data = null)
        {

            this.left = left;
            this.right = right;

        }
Exemple #2
0
        //4.3 Given a sorted(increasing order) array, write an algorithm to create a binary tree with minimal height

        static Tree addToTree(int[] arr, int start, int end) {

            if (end > start) {
                return null;
            }

            int mid = (start + end) / 2;
            var left = addToTree(arr, start, mid - 1);
            var right = addToTree(arr, mid + 1, end);

            var n = new Tree(left, right, mid);

            return n;
        }
Exemple #3
0
        //4.4 Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists).

        static Dictionary<int, List<Tree>> createLevelsList(Tree root, int level = 0) {

            var res = new Dictionary<int, List<Tree>>();

            var left = root.left;
            var right = root.right;

            if (left != null) {

                //res.Add

            }

            var llist = createLevelsList(left, level + 1);
            var rlist = createLevelsList(right, level + 1);

            
           
            return res;
        }
Exemple #4
0
 static bool isBalanced(Tree node) {
     return Tree.findMaxDep(node.left) - Tree.findMinDep(node.right) <= 1;
 }
Exemple #5
0
 private static int findMinDep(Tree node)
 {
     if (node == null)
         return 0;
     return 1 + Math.Min(findMinDep(node.left), findMinDep(node.right));
 }
        public int treeHeight(Tree T)
        {
            if (T == null) return 0;
            int leftHeight = 0;
            if (T.left != null)
                leftHeight = 1 + treeHeight(T.left);
            int rightHeight = 0;
            if (T.right != null)
                rightHeight = 1 + treeHeight(T.right);

            return leftHeight > rightHeight ? leftHeight : rightHeight;
        }