劍指offer-------之字列印二叉樹
阿新 • • 發佈:2018-12-13
題目:
思路:
程式碼:
struct TreeNode { int val; TreeNode *left; TreeNode *right; } void Print(BinaryTreeNOde* pRoot) { if(pRoot == NULL) return; stack<BinaryTreeNOde*>levels[2]; int current = 0; int next = 1; levels[current].push(pRoot); while(!levels[0].empty() || !levels[0].empty()) { BinaryTreeNOde* pNode = levels[current].top(); levels[current].pop(); printf("%d",pNode->val); if(current == 0) { if(pNode->left != NULL) levels[next].push(pNode->left); if(pNode->right != NULL) levels[next].push(pNode->right); } else { if(pNode->right != NULL) levels[next].push(pNode->right); if(pNode->left != NULL) levels[next].push(pNode->left); } if(levels[current].empty()) { printf("\n"); current = 1-current; next = 1-next; } } }