Rewrite part of the code from C+ to Python



  • How can I rewrite this C++ code in Python?

    void treeFork(treeNode* root)
    {
        if (root)
        {
            treeFork(root->left);
            if (root->left && root->right)
                cout << root->data << " ";
            treeFork(root->right);
        }
    }
    

    Here's my Python code.

    class Node:
       def init(self, data):
          self.left = None
          self.right = None
          self.data = data
    

    def insert(self, data):
    if self.data:
    if data < self.data:
    if self.left is None:
    self.left = Node(data)
    else:
    self.left.insert(data)
    elif data > self.data:
    if self.right is None:
    self.right = Node(data)
    else:
    self.right.insert(data)
    else:
    self.data = data

    def fork(root):
    if root is None:
    return 0
    else:
    if root.left and root.right:
    print(root.data)

    m, *n = map(int, input().split())
    root = Node(m)
    for i in n:
    if i!=0:
    root.insert(i)

    print(str(fork(root)))

    I need to rewrite the part with the function def fork(root)

    The point is, the code has to remove all the wood dissolving. In my code, it only removes the root, but it doesn't go any further.
    Thank you for your help.



  • Where have you lost your job?

    def fork(root):
        if root is None:
            return 0 
        else:
            fork(root.left)              # <<<<
            if root.left and root.right:
                print(root.data)
            fork(root.right)             # <<<<
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2