题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
其实树就四种经典的遍历算法吧,前序,中序,后序,顺序遍历。顺序只能非递归吧,其实这四种算法的
非递归都很相似,都是用stack和queue来完成。其实如果想学非递归的实现方法并不复杂,只需要弄懂一个,
其他的顺推就行。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> answer;
queue<TreeNode *> ab;
TreeNode *pp=root;
if(root)
ab.push(pp);
else
return answer;
while(!ab.empty())
{
answer.push_back(ab.front()->val);
if(ab.front()->left)
ab.push(ab.front()->left);
if(ab.front()->right)
ab.push(ab.front()->right);
ab.pop();
}
return answer;
}
};
查看14道真题和解析