博文中会简要介绍Leetcode P0144题目分析及解题思路。
“Binary Tree Preorder Traversal”是一道比较基础的题目,这道题考察的目标很明确,要求分别用迭代和递归的方法实现对二叉树的前序遍历。
Given a binary tree, return the preorder traversal of its nodes’ values.
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> preorder = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
// Find the deepest left subtree
while (curr != null) {
preorder.add(curr.val);
stack.offerFirst(curr);
curr = curr.left;
}
curr = stack.pollFirst();
curr = curr.right;
}
return preorder;
}
}
以下是C++的题解代码实现。
/**
* 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:
vector<int> preorderTraversal(TreeNode* root) {
this->_Dfs(root);
return this->preorder_;
}
private:
vector<int> preorder_;
void _Dfs(TreeNode *curr) {
if (!curr)
return;
this->preorder_.push_back(curr->val);
if (curr->left)
this->_Dfs(curr->left);
if (curr->right)
this->_Dfs(curr->right);
}
};