当前位置:网站首页>94. Middle order traversal of binary tree

94. Middle order traversal of binary tree

2022-07-27 00:08:00 happykoi

94. Middle order traversal of binary trees

date :2022/7/17

Title Description : Given the root node of a binary tree root , return its Middle preface Traverse .

Example :

 Input :root = [1,null,2,3]
 Output :[1,3,2]

 Input :root = []
 Output :[]

 Input :root = [1]
 Output :[1]

Ideas :

 Recursion and backtracking 

Code + analysis :

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
  recursive 
 */
class Solution {
public:
    void inorder(TreeNode* root, vector<int>& res){   //res The address of 
        if(root == nullptr) return;
        inorder(root->left,res);   
        res.push_back(root->val);   // Middle preface 
        inorder(root->right,res);
    }

    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inorder(root,res);
        return res;
    }
};
// iteration 
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stk;   // Stack ( Last in, first out )
        while (root != nullptr || !stk.empty()) {
            while (root != nullptr) {  // Always traverse the left subtree 
                stk.push(root);
                root = root->left;
            }
            root = stk.top();   // Back to previous 
            stk.pop();  // Pop up the top node, That is, the leftmost one of the subtree 
            res.push_back(root->val);
            root = root->right;  // Start traversing the right subtree of the node 
        }
        return res;
    }
};

Summary of learning :

  1. In the sequence traversal ( recursive + iteration )
  2. res In front &
原网站

版权声明
本文为[happykoi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207180758210199.html