技术交流可以加:
本人微信:xcg852390212
本人qq:852390212
学习交流qq群1(已满): 962535112
学习交流qq群2: 780902027
二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解答
方法1:递归
C++代码
/**
* 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:
void preorder(TreeNode* root,vector<int>& vec)
{
if(!root) return;
vec.push_back(root->val);
preorder(root->left,vec);
preorder(root->right,vec);
}
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, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.preOrder(root,res)
return res
def preOrder(self,root,lt: List[int]):
if root is None:
return
lt.append(root.val)
self.preOrder(root.left,lt)
self.preOrder(root.right,lt)
方法2:迭代
思路:对每个结点按照 根->右->左 的顺序入栈,出栈的顺序就是前序遍历的结果。
C++代码
/**
* 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) {
if(!root)
return vector<int>();
vector<int> res;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty())
{
TreeNode* head = sta.top();
sta.pop();
res.push_back(head->val);
if(head->right)
sta.push(head->right);
if(head->left)
sta.push(head->left);
}
return res;
}
};
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]:
if root is None:
return []
sta = []
res = []
sta.append(root)
while len(sta) > 0:
tmp = sta.pop()
res.append(tmp.val)
if tmp.right:
sta.append(tmp.right)
if tmp.left:
sta.append(tmp.left)
return res