Order traversal binary tree in classical algorithm

1. Topic description
Given a binary tree, return its mid-order traversal.

Example:

Input: [. 1, null, 2,3]
. 1

2
/
. 3

Output: [1,3,2]
Advanced: Recursive algorithm is very simple, can you complete iterative algorithm?

2. My code
/ **

  • Definition for a binary tree node.

  • struct TreeNode {

  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    class Solution {
    public:
    vector inorderTraversal(TreeNode
    root) {

     if(root == NULL)
         return result_vec;
     if(root->left != NULL){
         inorderTraversal(root->left);
     }
     result_vec.push_back(root->val);
     if(root->right != NULL) {
         inorderTraversal(root->right);
     }
     return result_vec;
    

    }
    vector result_vec;
    };

3. A good solution
on the Internet a. Stack-based traversal
/ **

  • Definition for a binary tree node.

  • struct TreeNode {

  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    /
    class Solution {
    public:
    vector inorderTraversal(TreeNode
    root) {
    stack<TreeNode*> node_stack;
    TreeNode* cur_node = root;

     if(root == NULL)
         return result_vec;
    
     while(cur_node != NULL || !node_stack.empty()){
         while(cur_node != NULL){
             node_stack.push(cur_node);
             cur_node = cur_node->left;
         };
         cur_node = node_stack.top();
         node_stack.pop();
         result_vec.push_back(cur_node->val);
         cur_node = cur_node->right;
     };
     return result_vec;
    

    }
    vector result_vec;
    };
    b. Morris traversal

4. What you can improve

5. Optimize the code to be
incomprehensible. The method of using the stack.
6. The thinking obtained. The
logic of the recursive method is clear, but the memory occupation and execution efficiency are not ideal. The
logic of the Morris traversal method is slightly more complicated. In addition, it will change the binary tree. Just fine

Published 4 original articles · Likes0 · Visits 23

Guess you like

Origin blog.csdn.net/digitaluser/article/details/105616190