本题和上题一样同属于层次遍历,不同的是本题从底层往上遍历,如下:
代码如下:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode():val(),left(NULL),right(NULL){}
TreeNode(int x): val(x), left(NULL),right(NULL) {}
}; vector<vector<int> > levelOrderTraversalII(TreeNode *root) //非递归的中序遍历(用栈实现)
{ queue<TreeNode *> tree_queue;
vector<vector<int> > tree_vector, tree_rvector;
vector<int> svector;
int nCount = ; if (NULL == root) {
return tree_vector;
}
TreeNode *pTemp = root;
tree_queue.push(root);
tree_queue.push(NULL); //the end of one level. while (true) {
TreeNode *pTemp = tree_queue.front();
tree_queue.pop(); if (!pTemp) { //get the null, put vector<> to vector<vector<>>
tree_vector.push_back(svector);
nCount ++;
svector.clear();
if (tree_queue.empty())
break;
tree_queue.push(NULL);
}
else {
svector.push_back(pTemp->val);
if (pTemp->left)
tree_queue.push(pTemp->left);
if (pTemp->right)
tree_queue.push(pTemp->right);
}
}
while (nCount > ){
svector = tree_vector.at(nCount - );
tree_rvector.push_back(svector);
nCount --;
}
return tree_rvector;
}