力扣算法题—144Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1
\
2
/
3 Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

Solution:

  很简单,使用栈,先存入右节点,再存入左节点,这样就是先弹出左节点了

  

 class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr)return {};
vector<int>res;
stack<TreeNode*>s;
s.push(root);
while (!s.empty())
{
TreeNode* p = s.top();
s.pop();
res.push_back(p->val);
if (p->right)s.push(p->right);
if (p->left)s.push(p->left);
}
return res;
}
};
上一篇:CentOS 6.4 升级python 2.6.6 到 python 2.7.9


下一篇:出现could not find developer disk image解决办法和不受信任的开发者