用非递归方式编码对一个二叉树的前、中、后、层次遍历。

牛客网瓜子2019笔试题,

仅用来复习二叉树遍历

#include
using namespace std;

struct TreeNode {
    int val;
    int left;
    int right;
}t[1000];
int vis[1000];
int ans[1000];
void preOrder(TreeNode root) {
    stack q;
    q.push(root);
    int k = 0;
    while(!q.empty()) {
        TreeNode pNode = q.top();
        q.pop();
        ans[k++] = pNode.val;
        if(pNode.right)
            q.push(t[pNode.right]);
        if(pNode.left)
            q.push(t[pNode.left]);
    }
}
void inOrder(TreeNode root) {
    stack q;
    q.push(root);
    int k = 0;
    memset(vis, 0, sizeof(vis));
    vis[root.val] = 1;
    while(!q.empty()) {
        TreeNode pNode = q.top();
        if(pNode.left && !vis[pNode.left]) {
            q.push(t[pNode.left]);
        } else {
            q.pop();
            ans[k++] = pNode.val;
            vis[pNode.val] = 1;
            if(pNode.right) {
                q.push(t[pNode.right]);
            }
        }
    }
}
void postOrder(TreeNode root) {
	stack q, p;
	q.push(root);
	int k = 0;
	while(!q.empty()) {
		TreeNode pNode = q.top();
		q.pop();
		p.push(pNode);
		if(pNode.left != 0)
            q.push(t[pNode.left]);
        if(pNode.right != 0)
            q.push(t[pNode.right]);
	}
	while(!p.empty()) {
        ans[k++]=p.top().val;
        p.pop();
    }
    
}
void Order(TreeNode root) {
	queue q;
    q.push(root);
    int k=0;
    while(!q.empty()) {
        TreeNode now=q.front();
        q.pop();
        ans[k++]=now.val;
        if(now.left!=0)
        q.push(t[now.left]);
        if(now.right!=0)
        q.push(t[now.right]);
    }
}
int main() {
    int n;
    while(~scanf("%d",&n)) {
        memset(vis,0,sizeof(vis));
        for(int i = 1; i <= n; i++) {
            int a, b;
            scanf("%d%d",&a,&b);
            t[i].left=a;
            t[i].right=b;
            t[i].val=i;
            vis[a]=1;
            vis[b]=1;
        }
        int root;
        for(int i = 1; i <= n; i++) {
            if(vis[i] == 0) {
                root = i;
                break;
            }
        }
        preOrder(t[root]);
        for(int i = 0;i < n-1; i++) {
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[n-1]);
        
        inOrder(t[root]);
        for(int i = 0;i < n-1; i++) {
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[n-1]);
        
        postOrder(t[root]);
        for(int i = 0;i < n-1; i++) {
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[n-1]);
        
        Order(t[root]);
        for(int i = 0; i < n-1;i++) {
            printf("%d ",ans[i]);
        }
        printf("%d\n",ans[n-1]);
    }
}

 

你可能感兴趣的:(剑指)