// 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
// Description:
// Print all nodes in tree layer by layer
std::vector<int> PrintFromTopToBottom2(TreeNode* root) {
std::vector<int> vecRet ;
if(root == NULL) return vecRet ;
std::queue<TreeNode*> tQueue ;
tQueue.push(root) ;
int nLast = root->val ;
while(!tQueue.empty()) {
TreeNode* pNode = tQueue.front() ;
vecRet.push_back(pNode->val) ;
if(pNode->left)
tQueue.push(pNode->left) ;
if(pNode->right)
tQueue.push(pNode->right) ;
if(nLast == pNode->val) {// when equals nLast, all children of current layer have pushed into tQueue
nLast = tQueue.back()->val ;
vecRet.push_back(-1) ;// use -1 as the line delimiter
}
}
return vecRet ;
}
// Main Idea:
// Simple!!!!
// Print self then push his left and right child
vector<int> PrintFromTopToBottom(TreeNode* root) {
std::vector<int> vecRet ;
if(root == NULL)
return vecRet ;
std::queue<TreeNode*> tQueue ;
tQueue.push(root) ;
while(!tQueue.empty()) {// while
TreeNode* pNode = tQueue.front() ;
vecRet.push_back(pNode->val) ;// vecRet.push_back(pNode->val)
if(pNode->left != NULL)
tQueue.push(pNode->left) ;
if(pNode->right != NULL)
tQueue.push(pNode->right) ;
tQueue.pop() ;// tQueue.pop
}
return vecRet ;
}
};
从上往下打印二叉树
最新推荐文章于 2022-08-10 15:04:41 发布