递归:
c++
push_back()函数的用法
vector<int> vec;
vec.push_back(10); // 在Vector最后添加一个元素(参数为要插入的值)
string str;
str.push_back('d'); // 在string最后插入一个字符;
/* 类似的:
pop_back() //移除最后一个元素
clear() //清空所有元素
empty() //判断vector是否为空,如果返回true为空
erase() // 删除指定元素
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// 自己的函数
void preorder(TreeNode* root, vector<int>& res){ // 传入向量指针 &res
if(root==NULL){ // 递归终止的条件为碰到空节点
return;
}
res.push_back(root->val); // 将一个新的元素加到vector的最后面
preorder(root->left,res);
preorder(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root,res); // 子函数传入参数根节点
return res;
}
};
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res=[]
def preorder(root):
if not root:
return res
res.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return res
栈:
我们也可以用迭代的方式实现方法一的递归函数,两种方式是等价的,区别在于递归的时候隐式地维护了一个栈,而我们在迭代的时候需要显式地将这个栈模拟出来
c++
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr){
return res;
}
stack<TreeNode*> stk; // 创建一个栈
while(root!=nullptr || !stk.empty()){ // 节点为空且栈空,则已访问完最右节点,
while(root != nullptr){ // 找到最左节点
stk.push(root); // 将遍历到的左节点放到栈中
res.push_back(root->val); // 向结果中加入根
root = root->left; // 遍历下一个左节点
}
root = stk.top(); // 开始回溯,栈顶为最左(底)的节点
root = root->right; // 访问该根右节点
stk.pop(); // 访问完毕,出栈
}
return res;
}
};
python
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
stack = []
while root or stack:
while root: # 找到最左节点
stack.append(root)
res.append(root.val)
root = root.left # # 访问该根节点最左节点
# 开始回溯
root = stack[-1] # (遍历到最左节点时,while中root = root.left = nullptr)所以root从stack取
root = root.right # 访问该根节点右节点
stack.pop() # 访问完毕,出栈
return res