New answers tagged

1

Clean up allocated memory (everything newed should be deleted), or use smart pointers to do it for you. (Perhaps each tree node should own its children, and store them in unique_ptrs, and the parent should be a raw pointer). There doesn't seem to be any benefit to overloading operator new for the Tree class. Currently, the iterator is more of a sub-tree ...


2

Overall looks good, so take below as a few ideas, nothing's really wrong with it. Except using setf without a previous variable declaration, that's just not guaranteed to even work (assuming that's what the code snippet showed with (setf bst nil)). I'm gonna try this on CCL: Evaluating the structure definition gives me an unused warning for the d ...


1

Your method visits mosts nodes twice: Here int leftDiameter = DiameterOfBinaryTree(root.left); int rightDiameter = DiameterOfBinaryTree(root.right); int leftHeight = Height(root.left); int rightHeight = Height(root.right); calling DiameterOfBinaryTree on the left and right subtree determines the height of both subtrees, and then calling Height on the ...


0

Would it be better to unfold the reccursion to iteration? As I understand calculations are performed on back propagation (after you reached the leaf). With an iterative approcah you can avoid aditional stack allocation and perform calculations on forward propagation - no need to return to root in order to get the result. Update 1: According to letcode ...


0

It looks bad on multiple levels. It doesn't look like a decent C++ but closer to C. Use std::vector, std::map, and their functionality instead of memset... also passing ll tree[] as input parameter of a function is ill advised. Usage of recursion, it screws your performance and it is probably the source of bugs. Also static allocation of large arrays a and ...


4

Data structure-wise, it seems okay, and does what you're after. Code-style wise, I see a few things: It's not quite PEP8, the coding style. Whilst you can read it, which is always good, there are tools to automatize the process, such as flake8, black. Most likely, your editor will have a plugin. This is include things like underscore_names in lieu of ...


2

I don't mean to drag this up but have you considered a recursion function? Not so long ago I created a binary CART model in VBA that uses a basic recursive structure along the lines of:- Function A - Call function B to add row to output recordset object - Check for leaf conditions; exit function early if yes - Call function C to calculate best split and ...


2

Iterators This is wrong: class BinarySort: def __iter__(self) -> None: ''' Calls the _inorder traversing method recursively; ''' self._inorder(self.root) def _inorder(self, parent_node: Node) -> None: ... In this answer, I suggested instead of creating a function for printing the tree in order, you ...


3

Modules instead of "namespace" classes TreeSortingAlgorithms has no right to exist. It's good to want to put stuff in namespaces, but your nested classes are confusing and difficult-to-read. Instead, just put your algorithmic classes into a different file and use it as a module. That will get you a namespace but also be more legible, easier to deal with in ...


2

Encapsulating the wrong things insert and flatten should be methods on TreeNode. Solution doesn't particularly need to exist as a class. Those two methods can assume that self is the root. Return types As @Carcigenicate suggested: what do you return from flatten? Probably the return type hint should be changed to TreeNode, and you should modify your ...


3

To answer the question from the comment on RoToRa's answer: Thanks! I wonder if there is any way to do this by using, for example, just the Java 8 Stream API or something similar, to have it in just one line of code. Using the Java Stream API Assuming the following Entry class: public class Entry { final String key; final List<Entry> ...


1

**Code after the suggestion** 1. Class node class Node: 2. Constructor '''this is the constructor''' def __init__(self, data): self.left = None self.right = None self.data = data 3. Insert node def insert(self, data): ''' this function work is insert the data in bst''' if self.data: '''insert left side value ''' if data &...


3

A few quick points that came to my mind when looking at your code: Documentation Your code has no documentation whatsoever. Python has so called documentation strings, which are basically """triple quoted text blocks""" immediately following def whatever(...). Example: def print_tree(self): """Print the content of the tree This method performs an ...


2

First off, I'm assuming the call of the method flatEntriesMap is wrong and it should be a recursive call to flatTree. (EDIT: Source code has been corrected.) Then you should reconsider the name, especially considering the confusion before your edit: You are not flatting the tree, but retrieving its leaves. To get rid of the side effect, you simply make the ...


0

As pointed out by @RootToo: You are looping more times than needed. You loop n times for a list of length n, where you only need to be looping n.bit_length() times. The function may fail for a tree with an incomplete last layer. The additional point I'd like to cover is you are also comparing too much. With your binary tree [1,2,2,3,4,4,3], you check ...


4

Your testcases are far too simple to be certain your algorithm works. This might be an issue on the challenge's side. Both these testcases have symmetrical solutions. It's best to always rob every second layer. No test cases cover instances where the left side of the tree might follow a different pattern to the right side. Take for example the testcase: { 3,...


2

Two things: The function may fail for a tree with an incomplete last layer. For example: is_symmetric([1, 2, 2, 3, 4, 3]) returns True, but it should be False. This can be fixed by checking if layers have the expected length. if len(layer) != (end - start) or layer != list(reversed(layer)): return False The for loop iterates more times than ...


1

Pretty good! Only two points: Remove your parens from this - end = (2 ** interval) - 1 due to order of operations. Also, your function is a good candidate for doc tests. Read up here: https://docs.python.org/3.7/library/doctest.html This will allow you to move your asserts into the docstring of the function itself.


6

Performance The recursive function is as fast as I can think of. The iterative function should enqueue root.left and root.right instead of root and root to gain a cycle (micro-optimisation). Review I find it weird that the null node is considered symmetric IsSymmetric(null). I would throw an error for invalid input. Both algorithms are not able to deal ...


Top 50 recent answers are included