链接
思路
递归
c++
1.递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> result;
void tra(vector<int> &result, TreeNode* root){
if(root == NULL){
return;
}
result.push_back(root->val);
tra(result, root->left);
tra(result, root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
tra(result, root);
return result;
}
};
效率蛮高的,打败100%
2.非递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root)
{
TreeNode *tem;
vector<int> result;
stack<TreeNode *> q;
q.push(root);
while(!q.empty()){
tem = q.top();
q.pop();
if(tem != NULL){
result.push_back(tem->val);
q.push(tem->right);
q.push(tem->left);
}
}
return result;
}
};
python
参考网友的写法
栈的妙用。真的很巧妙啊。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
stack = [root]
res = []
while stack:
tem = stack.pop()
if tem:
res.append(tem.val)
stack.append(tem.right)
stack.append(tem.left)
return res