What is the logic for traversing each and every path in a binary tree in C++? [closed]

StackOverflow https://stackoverflow.com/questions/20139098

  •  03-08-2022
  •  | 
  •  

Domanda

This is my first time i am studying binary trees, and i see a lot of questions regarding the path traversal, one such question was to find the path of a particular node. This is very easy in a Binary Search Tree, but it's very tough in a normal Binary Tree as the elements in the nodes have no relation between. I came up with many logic but none of them work for all the nodes in the tree. And i would also like to know what is the logic for traversing each and every path from the root to the leaf node.

Thank You.

È stato utile?

Soluzione

Use recursion. The details vary depending on exactly how you've defined your tree, but it might look something like this

void visit(TreeNode* node, vector<Node*>& path)
{
    // check for NULL
    if (node == NULL)
        return;
    // add node to path
    path.push_back(node);
    // print the node path
    ...
    // visit left child
    visit(node->left, path);
    // visit right child
    visit(node->right, path);
    // remove node from path
    path.pop_back();
}

// start at the root
vector<Node*> path;
visit(root, path);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top