How to iterate through a binary search tree python

So far I have

def tree_iterate[]:
parent, current = None, self.root
lst = []
while current is not None: 
 if current.left not None:
  lst.append[current.item] 
  parent, current = current, current.left
 if current.right not None:
  lst.append[current.item]
  parent, current = current, current.right

[sorry about spacing I'm quite new at this]

I'm not quite sure how to iterate on both sides of the tree when current has left and right, without using recursion. My main goal is to have a list of all the nodes in this BSTenter code here

asked Mar 31, 2014 at 1:55

1

To get a list of all nodes in the BST iteratively, use Breadth-First Search [BFS]. Note that this won't give you the nodes in sorted order:

queue = [root]
result = []
while queue:
    l = queue.pop[0]
    result.append[l]

    if l.left != None:
        queue.append[l.left]
    if l.right!= None:
        queue.append[l.right]

If you want the nodes in sorted order, you will need to simulate inorder traversal using a stack:

result = []
stack = [root]
while stack:
    stack[-1].visited = True
    if stack[-1].left != None and not stack[-1].left.visited:
        stack.append[stack[-1].left]
    else:
        node = stack.pop[]
        result.append[node]
        if stack[-1].right != None:
            stack.append[stack[-1].right]

answered Mar 31, 2014 at 2:17

spinlokspinlok

3,46316 silver badges25 bronze badges

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a binary search tree and a key. Check the given key exists in BST or not without recursion.

    Please refer binary search tree insertion for recursive search. 

    C++

    #include

    using namespace std;

    struct Node {

        int data;

        struct Node *left, *right;

    };

    bool iterativeSearch[struct Node* root, int key]

    {

        while [root != NULL] {

            if [key > root->data]

                root = root->right;

            else if [key < root->data]

                root = root->left;

            else

                return true;

        }

        return false;

    }

    struct Node* newNode[int item]

    {

        struct Node* temp = new Node;

        temp->data = item;

        temp->left = temp->right = NULL;

        return temp;

    }

    struct Node* insert[struct Node* Node, int data]

    {

        if [Node == NULL]

            return newNode[data];

        if [data < Node->data]

            Node->left = insert[Node->left, data];

        else if [data > Node->data]

            Node->right = insert[Node->right, data];

        return Node;

    }

    int main[]

    {

        struct Node* root = NULL;

        root = insert[root, 50];

        insert[root, 30];

        insert[root, 20];

        insert[root, 40];

        insert[root, 70];

        insert[root, 60];

        insert[root, 80];

        if [iterativeSearch[root, 15]]

            cout Node.data]

                Node.right = insert[Node.right, data];

            return Node;

        }

        public static void main[String args[]]

        {

            Node root = null;

            root = insert[root, 50];

            insert[root, 30];

            insert[root, 20];

            insert[root, 40];

            insert[root, 70];

            insert[root, 60];

            insert[root, 80];

            if [iterativeSearch[root, 15]]

                System.out.println["YES"];

            else

                System.out.println["NO"];

        }

    }

    Python3

    class newNode:

        def __init__[self, data]:

            self.data = data

            self.left = None

            self.right = None

    def iterativeSearch[root, key]:

        while root != None:

            if key > root.data:

                root = root.right

            elif key < root.data:

                root = root.left

            else:

                return True

        return False

    def insert[Node, data]:

        if Node == None:

            return newNode[data]

        if data < Node.data:

            Node.left = insert[Node.left, data]

        elif data > Node.data:

            Node.right = insert[Node.right, data]

        return Node

    if __name__ == '__main__':

        root = None

        root = insert[root, 50]

        insert[root, 30]

        insert[root, 20]

        insert[root, 40]

        insert[root, 70]

        insert[root, 60]

        insert[root, 80]

        if iterativeSearch[root, 15]:

            print["Yes"]

        else:

            print["No"]

    C#

    using System;

    class GFG {

        public class Node {

            public int data;

            public Node left, right;

        };

        static bool iterativeSearch[Node root, int key]

        {

            while [root != null] {

                if [key > root.data]

                    root = root.right;

                else if [key < root.data]

                    root = root.left;

                else

                    return true;

            }

            return false;

        }

        static Node newNode[int item]

        {

            Node temp = new Node[];

            temp.data = item;

            temp.left = temp.right = null;

            return temp;

        }

        static Node insert[Node Node, int data]

        {

            if [Node == null]

                return newNode[data];

            if [data < Node.data]

                Node.left = insert[Node.left, data];

            else if [data > Node.data]

                Node.right = insert[Node.right, data];

            return Node;

        }

        public static void Main[String[] args]

        {

            Node root = null;

            root = insert[root, 50];

            insert[root, 30];

            insert[root, 20];

            insert[root, 40];

            insert[root, 70];

            insert[root, 60];

            insert[root, 80];

            if [iterativeSearch[root, 15]]

                Console.WriteLine["YES"];

            else

                Console.WriteLine["NO"];

        }

    }

    Javascript

    class Node {

        constructor[] {

            this.data = 0;

            this.left = null;

            this.right = null;

        }

    }

        function iterativeSearch[root , key]

        {

            while [root != null] {

                if [key > root.data]

                    root = root.right;

                else if [key < root.data]

                    root = root.left;

                else

                    return true;

            }

            return false;

        }

        function newNode[item]

        {

            var temp = new Node[];

            temp.data = item;

            temp.left = temp.right = null;

            return temp;

        }

        function insert[Node , data]

        {

            if [Node== null]

                return newNode[data];

            if [data < Node.data]

                Node.left = insert[Node.left, data];

            else if [data > Node.data]

                Node.right = insert[Node.right, data];

            return Node;

        }

            var root = null;

            root = insert[root, 50];

            insert[root, 30];

            insert[root, 20];

            insert[root, 40];

            insert[root, 70];

            insert[root, 60];

            insert[root, 80];

            if [iterativeSearch[root, 15]]

                document.write["YES"];

            else

                document.write["NO"];


    How do you iterate a binary tree in Python?

    An easy iterative way to get all the nodes in your tree is to use breadth first search [BFS]. You can use a queue [a simple python list] for this.

    How do you iterate through BST?

    Implementing Backward Iterator in BST..
    Implementing Forward Iterator in BST..
    Find a pair with given sum in a Balanced BST..
    Find a pair with given sum in BST..
    Maximum element between two nodes of BST..
    Find pairs with given sum such that pair elements lie in different BSTs..
    Find the closest element in Binary Search Tree..

    How do you traverse through a tree in Python?

    Pre-order Traversal In this traversal method, the root node is visited first, then the left subtree and finally the right subtree. In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then we create a insert function to add data to the tree.

    How do you traverse all the nodes in a binary tree?

    Use DFS to traverse the tree and maintain height for the current node..
    If the Node is NULL then return;.
    If level is 1 print[tree->data];.
    Else if the level is greater than 1, then. Recursively call to for tree->left, level-1. Recursively call to for tree->right, level-1..

    Chủ Đề