java - Time and space complexity of this function to print binary tree level by level -
this algorithm printing common binary tree level level.
what time complexity , space complexity of printspecificlevel_bt() , printbt_lbl()?
i think printspecificlevel_bt's time complexity o(lg n), , space complexity o(lg n).
think printbt_lbl()'s time complexity o((lgn)^2), , space complexity o((lgn)^2).
is correct?
// print specific level of binary tree. public static void printspecificlevel_bt (node root, int level) { if (root == null) return; if (level == 0) system.out.print(string.format("%-6d", root.data)); // base case. // recrusion. printspecificlevel_bt(root.leftch, level - 1); printspecificlevel_bt(root.rightch, level - 1); } // height of binary tree. public static int getheight_bt (node root) { if (root == null || (root.leftch == null && root.rightch == null)) return 0; // base case. return 1 + math.max (getheight_bt(root.leftch), getheight_bt(root.rightch)); } // print binary tree level level. public static void printbt_lbl (node root) { // height of binary tree. int height = getheight_bt(root); (int = 0; <= height; ++) { printspecificlevel_bt(root, i); system.out.println(); } }
printspecificlevel_bt o(n) since looks @ every node in tree. however, change (returning when level == 0), can make o(min(n, 2^level)).
getheight o(n) since looks @ every node in tree. printbt_lbl calls getheight once , printspecificlevel_bt height times, complexity o(n + n*height) = o(n*height).
the space complexity of each o(height) since recurses way bottom of tree. can't o(log n) since tree isn't balanced (unless is).
Comments
Post a Comment