题目地址:Binary Tree Preorder Traversal - LeetCode
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?
经典的二叉树前续遍历,递归解法最容易想到。
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]:
def helper(root, l):
if root is None:
return
l.append(root.val)
helper(root.left,l)
helper(root.right,l)
l = []
helper(root, l)
return l
迭代的解法要复杂一些,要用到栈。
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]:
l = []
if root is None:
return l
stack=[root]
while stack!=[]:
temp=stack.pop()
if temp is not None:
l.append(temp.val)
if temp.right is not None:
stack.append(temp.right)
if temp.left is not None:
stack.append(temp.left)
return l
时间复杂度为O(n),空间复杂度为O(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:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> l;
l.push(root);
while (!l.empty()) {
TreeNode *temp = l.top();
l.pop();
if (temp == nullptr) {
continue;
}
result.push_back(temp->val);
if (temp->right != nullptr) {
l.push(temp->right);
}
if (temp->left != nullptr) {
l.push(temp->left);
}
}
return result;
}
};