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

Leetcode94. Middle order traversal of binary trees

2022-07-07 22:49:00 Qingshan's green shirt

LeetCode94. Middle order traversal of binary trees

1. problem

 Insert picture description here

2. Ideas

(1) What is middle root traversal

 Insert picture description here

(2) recursive

The same idea as before and after !

(3) iteration

It takes a stack !
 Insert picture description here  Insert picture description here

a section ADL Pseudo code !
 Insert picture description here

Process simulation
 Insert picture description here

3. Code implementation

(1) recursive

 class Solution {
    
public:
    void inOrder(TreeNode*cur,vector<int>& vec)
    {
    
        if(cur == NULL)return;
        inOrder(cur->left,vec);// Left 
        vec.push_back(cur->val);// root 
        inOrder(cur->right,vec);// Right  
    }

    vector<int> inorderTraversal(TreeNode* root) {
    
        vector<int> result;
        inOrder(root, result);
        return result;
    }
};

(2) iteration

class Solution{
    
	public:
		vector<int> inorderTraversal(TreeNode* root){
    
			vector<int> result;
			stack<TreeNode*> st;// Create a stack 
			TreeNode* cur = root;
			while(1)
			{
    
				while(cur != NULL){
    // Every time you join one , First judge whether it can go down left , If there is one, put 
				st.push(cur);// Down the left branch , The visited node is put on the stack 
				cur = cur->left;  
			}
			if(st.empty()) return result;// When the stack is empty, it returns !
			cur = st.top();// If the last step cur->right Empty finger , Then here will continue to stack 
			st.pop();
			result.push_back(cur->val);
			cur = cur->right;
	}
}
};
原网站

版权声明
本文为[Qingshan's green shirt]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130603147262.html