두 갈래 나무의 앞, 중, 뒤, 단계를 비귀속 방식으로 인코딩합니다.

2927 단어 검지
뉴커넷 해바라기씨 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
",ans[n-1]); inOrder(t[root]); for(int i = 0;i < n-1; i++) { printf("%d ",ans[i]); } printf("%d
",ans[n-1]); postOrder(t[root]); for(int i = 0;i < n-1; i++) { printf("%d ",ans[i]); } printf("%d
",ans[n-1]); Order(t[root]); for(int i = 0; i < n-1;i++) { printf("%d ",ans[i]); } printf("%d
",ans[n-1]); } }

좋은 웹페이지 즐겨찾기