中序遍历二叉树

//中序遍历1
#include<stack>
void inorder(TreeNode* root){//注意p的更新!
	if(!root) return;
    stack<TreeNode*> stk;
    stk.push(root);
    TreeNode* p;
    while(!stk.empty()){
		while(p=stk.top()){//上一轮外循环p的右子树为空时可跳过该内循环
			stk.push(p->left);//直接压栈 由循环条件判断
		}
        stk.pop();
        if(!stk.empty()){
            p=stk.top();///
            stk.pop();
            cout<<p->val;//任意访问操作

            stk.push(p->right);//
        }
	}
}
//中序遍历2
#include<stack>
void inorder(TreeNode* root){//注意p的更新!
	if(!root) return;
    stack<TreeNode*> stk;
    TreeNode* p=root;//
    while(!stk.empty()||p){//
		while(p){
			stk.push(p);
			p=p->left;//
		}
        
        p=stk.top();///
        stk.pop();
        cout<<p->val;//任意访问操作

        p=p->right;//
        
	}
}


猜你喜欢

转载自blog.csdn.net/chailyn_trista/article/details/79934153
今日推荐