Iterative traversal of binary tree

Iterative traversal of binary tree

Title Link

144. Preorder traversal of binary tree (simple)

94. Middle order traversal of binary tree (simple)

145. Post order traversal of binary tree (simple)

Problem solution

Iterative method (non recursive method) is used to traverse the front, middle and rear order of binary tree.

The implementation of recursion is: each recursive call will press the local variables, parameter values and return addresses of the function into the call stack, and then when the recursion returns, the parameters of the last recursion will pop up from the top of the stack. Therefore, this is why recursion can return to the upper layer.

Preorder traversal (iterative method)

Idea: the preorder traversal is about the middle node. Each time, the intermediate node is processed first. First put the root node into the stack, then add the right child to the stack, and then add the left child. Only in this way can we ensure that the order of the stack is left and right. As follows:

Code (C + +):

//Preorder traversal of binary tree(iteration)
class Solution1 {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        //First, define a stack. The type of elements stored in the stack is a pointer to the tree node
        stack<TreeNode*> sta;
        //Define another vector,Used to store results
        vector<int> result;
        if (root == nullptr) return result;
        else sta.push(root);
        while (!sta.empty()) {
            result.push_back(sta.top()->val); //root
            TreeNode *node = sta.top();
            sta.pop();
            //Note that when the left node or right node is empty, it is not stacked
            if(node->right != nullptr) sta.push(node->right); //right
            if(node->left != nullptr) sta.push(node->left); //Left
        }
        return result;
    }
};

analysis:

  • Time complexity: O(n), where n is the number of nodes of the binary tree

  • Spatial complexity: O(n), which is the overhead of explicit stack during iteration. On average, it is O(logn). In the worst case, the tree is chain like, which is O(n).

Medium order traversal (iterative method)

Idea:

You can't directly change the order of the preceding traversal code to realize the middle order traversal.

There are two operations in the preceding traversal:

  1. Processing: put the element into the result array

  2. Accessing: traversing nodes

The pre order traversal order is about the middle. The first accessed elements are intermediate nodes, and the elements to be processed are also intermediate nodes. Therefore, relatively concise code can be written, because the order of the elements to be accessed and the elements to be processed are consistent, and they are intermediate nodes.

The middle order traversal is left, middle and right. First, the node at the top of the binary tree is accessed, and then access down layer by layer until it reaches the bottom of the left side of the tree, and then start processing the node (that is, putting the value of the node into the result array), which leads to the inconsistency between the processing order and the access order.

When using the iterative method to write the middle order traversal, you need to borrow the traversal of the pointer to help access the node, and the stack is used to process the elements on the node. As follows:

Code (C + +):

//Middle order traversal of binary tree(iteration)
class Solution2 {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> sta;
        vector<int> result;
        TreeNode* node = root;
        while (node != nullptr || !sta.empty()) {
            if (node != nullptr) {
                sta.push(node);
                node = node->left;
            } else {
                node = sta.top();
                sta.pop();
                result.push_back(node->val);
                node = node->right;
            }
        }
        return result;
    }
};

analysis:

  • Time complexity: O(n), where n is the number of binary tree nodes.

  • Spatial complexity: O(n). The spatial complexity depends on the stack depth. In the worst case, the tree is chain, which is O(n).

Postorder traversal (iterative method)

Idea: the first order traversal is left and right, and the subsequent traversal is left and right, so you only need to adjust the code order of the first order traversal to become the middle, right and left traversal order, and then reverse the result array, and the output result order is left and right, as shown in the following figure:

Code (C + +):

//Binary Tree Postorder Traversal (iteration)
class Solution3 {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> sta;
        vector<int> result;
        if (root == nullptr) return result;
        else sta.push(root);
        while (!sta.empty()) {
            TreeNode* node = sta.top();
            sta.pop();
            result.push_back(node->val);
            if(node->left != nullptr) sta.push(node->left);
            if(node->right != nullptr) sta.push(node->right);
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

analysis:

  • Time complexity: O(N)

  • Space complexity: O(N) (worst case)

Reference link

Code Capriccio

 

 

Tags: leetcode

Posted on Fri, 26 Nov 2021 11:07:38 -0500 by ares