Pre-Order tree Traverse.
1.中左右
两种方法
1. Recurisve
class Solution {
public:
vector<int> result;
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr)
return result;
result.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return result;
}
};
1. 函数结尾的return 并不会突出整个函数 只是退回上一层 这个经常犯错 如果函数返回类型是void 就不用写 自己也能推到上层。
2. 这个递归 天然就是为这道题设计的 因为发现了nullptr 正好找到上一部分
2.iterative
不借助函数的 call stack 自己构建一个stack
<pre name="code" class="cpp">class Solution {
public:
vector<int> result;
vector<int> preorderTraversal(TreeNode* root) {
std::stack<TreeNode*> mystack;
if (root == nullptr)
{
return result;
}
mystack.push(root);// 这个check 很聪明 很有想法
while (!mystack.empty())
{
root = mystack.top();
mystack.pop();
// no need to check the nullptr 因为下面的代码已经保证了stack里面没有nullptr
result.push_back(root->val);
// nullptr 不放到stack里面
if (root->right != nullptr)
mystack.push(root->right);
if (root->left != nullptr)
mystack.push(root->left);
}
return result;
}
};