/* 题目: 分行按层自上向下呈之字形打印二叉树。第一行从左到右,第二行从右到左,第三行从左到右... */ /* 思路: 使用两个栈stack1和stack2。 stack1存储从左向右打印的节点,stack2存储从右向左打印的节点。 stack1中pop的节点,按照先插入左节点再插入右节点的顺序到stack2中。 stack2与之相反。 */ #include<iostream> #include<string.h> #include<algorithm> #include<cmath> #include<stdio.h> #include<vector> #include<stack> #include<queue> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; void Print(TreeNode* root){ if(root == nullptr) return; stack<TreeNode*> stack1; stack<TreeNode*> stack2; stack1.push(root); while(!stack1.empty() || !stack2.empty()){ while(!stack1.empty()){ TreeNode* temp = stack1.top(); cout<<temp->val<<" "; stack1.pop(); if(temp->left != nullptr){ stack2.push(temp->left); } if(temp->right != nullptr){ stack2.push(temp->right); } } cout<<endl; while(!stack2.empty()){ TreeNode* temp = stack2.top(); cout<<temp->val<<" "; stack2.pop(); if(temp->right!= nullptr){ stack1.push(temp->right); } if(temp->left != nullptr){ stack1.push(temp->left); } } cout<<endl; } } int main(){ TreeNode* node1 = new TreeNode(1); TreeNode* node2 = new TreeNode(2); TreeNode* node3 = new TreeNode(3); TreeNode* node4 = new TreeNode(4); TreeNode* node5 = new TreeNode(5); TreeNode* node6 = new TreeNode(6); node1->left = node2; node1->right = node3; node2->left = node4; node3->left = node5; node3->right = node6; Print(node1); }