当前位置:网站首页>408-Binary tree-preorder inorder postorder level traversal

408-Binary tree-preorder inorder postorder level traversal

2022-08-02 04:52:00 Cat hair has almost lost cat

存储结构

Can be sequential or chained,Basically use chains.
Sequential storage is mainly usediThe left child of the node is 2i,右孩子为2i+1.Leave it blank if you have it or not.It's okay to store a complete binary tree or a full binary tree,The storage space utilization of common trees is too low.
链式存储

typedef struct Node{
    
	ElemType data;
	Node * left;		//左孩子
	Node * right;		//右孩子
}BTNode, *BTree;

先序中序后序层次遍历

先序:根左右
中序:左根右
后序:右根左
层次:一层一层遍历

Preorder inorder postorder recursive code

void preOrder(BTree root){
    
	if (root != NULL)
		return;	
	visit(root);				//You can change the position of the three lines in different order.
	preOrder(root->left);
	preOrder(root->right);
}

Implemented using stacks and queues

//stack preorder
void preOrder(BTree root){
    
	Stack<BTree> s;
	s.push(root);
	while(root != NULL || !s.empty()){
    
		while (tmp != NULL){
    
			tmp = tmp->left;
			visit(tmp);
			s.push(tmp);
		}
		root = s.top();
		s.pop();
		root = root->right;
	}
}

//stack in-order
void inOrder(BTree root){
    
	Stack<BTree> s;
	s.push(root);
	while(root != NULL || !s.empty()){
    
		while (tmp != NULL){
    
			tmp = tmp->left;
			s.push(tmp);
		}
		root = s.top();
		s.pop();
		visit(root);
		root = root->right;
	}
}

//栈后序,来自leetcode官方.
class Solution {
    
public:
    vector<int> postorderTraversal(TreeNode *root) {
    
        vector<int> res;
        if (root == nullptr) {
    
            return res;
        }

        stack<TreeNode *> stk;
        TreeNode *prev = nullptr;
        while (root != nullptr || !stk.empty()) {
    
            while (root != nullptr) {
    
                stk.emplace(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            if (root->right == nullptr || root->right == prev) {
    
                res.emplace_back(root->val);
                prev = root;
                root = nullptr;
            } else {
    
                stk.emplace(root);
                root = root->right;
            }
        }
        return res;
    }
};

//Hierarchical traversal is implemented using queues
void levelOrder(BTree root){
    
	Queue<BTree> q;
	q.push(root);
	while (!q.emtpy()){
    
		BTree tmp = q.pop();
		visit(tmp);
		if (tmp->left)
			q.push(tmp->left);
		if (tmp->right)
			q.push(tmp->right);
	}
}
原网站

版权声明
本文为[Cat hair has almost lost cat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020324330590.html