Binary Tree Preorder Traversal

Tags: Tree, Stack, Medium

Question

Problem Statement

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

  1. 1
  2. \
  3. 2
  4. /
  5. 3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

题解1 - 递归

面试时不推荐递归这种做法。

递归版很好理解,首先判断当前节点(根节点)是否为null,是则返回空vector,否则先返回当前节点的值,然后对当前节点的左节点递归,最后对当前节点的右节点递归。递归时对返回结果的处理方式不同可进一步细分为遍历和分治两种方法。

Python - Divide and Conquer

  1. """
  2. Definition of TreeNode:
  3. class TreeNode:
  4. def __init__(self, val):
  5. this.val = val
  6. this.left, this.right = None, None
  7. """
  8. class Solution:
  9. """
  10. @param root: The root of binary tree.
  11. @return: Preorder in ArrayList which contains node values.
  12. """
  13. def preorderTraversal(self, root):
  14. if root == None:
  15. return []
  16. return [root.val] + self.preorderTraversal(root.left) \
  17. + self.preorderTraversal(root.right)

C++ - Divide and Conquer

  1. /**
  2. * Definition of TreeNode:
  3. * class TreeNode {
  4. * public:
  5. * int val;
  6. * TreeNode *left, *right;
  7. * TreeNode(int val) {
  8. * this->val = val;
  9. * this->left = this->right = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * @param root: The root of binary tree.
  17. * @return: Preorder in vector which contains node values.
  18. */
  19. vector<int> preorderTraversal(TreeNode *root) {
  20. vector<int> result;
  21. if (root != NULL) {
  22. // Divide
  23. vector<int> left = preorderTraversal(root->left);
  24. vector<int> right = preorderTraversal(root->right);
  25. // Merge
  26. result.push_back(root->val);
  27. result.insert(result.end(), left.begin(), left.end());
  28. result.insert(result.end(), right.begin(), right.end());
  29. }
  30. return result;
  31. }
  32. };

C++ - Traversal

  1. /**
  2. * Definition of TreeNode:
  3. * class TreeNode {
  4. * public:
  5. * int val;
  6. * TreeNode *left, *right;
  7. * TreeNode(int val) {
  8. * this->val = val;
  9. * this->left = this->right = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * @param root: The root of binary tree.
  17. * @return: Preorder in vector which contains node values.
  18. */
  19. vector<int> preorderTraversal(TreeNode *root) {
  20. vector<int> result;
  21. traverse(root, result);
  22. return result;
  23. }
  24. private:
  25. void traverse(TreeNode *root, vector<int> &ret) {
  26. if (root != NULL) {
  27. ret.push_back(root->val);
  28. traverse(root->left, ret);
  29. traverse(root->right, ret);
  30. }
  31. }
  32. };

Java - Divide and Conquer

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> preorderTraversal(TreeNode root) {
  12. List<Integer> result = new ArrayList<Integer>();
  13. if (root != null) {
  14. // Divide
  15. List<Integer> left = preorderTraversal(root.left);
  16. List<Integer> right = preorderTraversal(root.right);
  17. // Merge
  18. result.add(root.val);
  19. result.addAll(left);
  20. result.addAll(right);
  21. }
  22. return result;
  23. }
  24. }

Java - Traversal

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. private List<Integer> result = new ArrayList<Integer>();
  12. public List<Integer> preorderTraversal(TreeNode root) {
  13. if (root != null) {
  14. result.add(root.val);
  15. preorderTraversal(root.left);
  16. preorderTraversal(root.right);
  17. }
  18. return result;
  19. }
  20. }

源码分析

使用遍历的方法保存递归返回结果需要使用辅助递归函数traverse,将结果作为参数传入递归函数中,传值时注意应使用vector的引用。另外一个方法则是使用类的私有变量保存最终结果。
分治方法首先分开计算各结果,最后合并到最终结果中。
C++ 中由于是使用vector, 将新的vector插入另一vector不能再使用push_back, 而应该使用insert。
Java 中使用addAll方法.

复杂度分析

遍历树中节点,时间复杂度 O(n), 遍历的方法未使用额外空间,分治的方法生成了临时变量,最差情况下空间复杂度为 (n).

题解2 - 迭代

迭代时需要利用栈来保存遍历到的节点,纸上画图分析后发现应首先进行出栈抛出当前节点,保存当前节点的值,随后将右、左节点分别入栈(注意入栈顺序,先右后左),迭代到其为叶子节点(NULL)为止。

Python

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. # @param {TreeNode} root
  9. # @return {integer[]}
  10. def preorderTraversal(self, root):
  11. if root is None:
  12. return []
  13. result = []
  14. s = []
  15. s.append(root)
  16. while s:
  17. root = s.pop()
  18. result.append(root.val)
  19. if root.right is not None:
  20. s.append(root.right)
  21. if root.left is not None:
  22. s.append(root.left)
  23. return result

C++

  1. /**
  2. * Definition of TreeNode:
  3. * class TreeNode {
  4. * public:
  5. * int val;
  6. * TreeNode *left, *right;
  7. * TreeNode(int val) {
  8. * this->val = val;
  9. * this->left = this->right = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * @param root: The root of binary tree.
  17. * @return: Preorder in vector which contains node values.
  18. */
  19. vector<int> preorderTraversal(TreeNode *root) {
  20. vector<int> result;
  21. if (root == NULL) return result;
  22. stack<TreeNode *> s;
  23. s.push(root);
  24. while (!s.empty()) {
  25. TreeNode *node = s.top();
  26. s.pop();
  27. result.push_back(node->val);
  28. if (node->right != NULL) {
  29. s.push(node->right);
  30. }
  31. if (node->left != NULL) {
  32. s.push(node->left);
  33. }
  34. }
  35. return result;
  36. }
  37. };

Java

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> preorderTraversal(TreeNode root) {
  12. List<Integer> result = new ArrayList<Integer>();
  13. Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
  14. if (root != null) stack.push(root);
  15. while (!stack.isEmpty()) {
  16. root = stack.pop();
  17. result.add(root.val);
  18. if (root.right != null) stack.push(root.right);
  19. if (root.left != null) stack.push(root.left);
  20. }
  21. return result;
  22. }
  23. }

源码分析

  1. 对root进行异常处理
  2. 将root压入栈
  3. 循环终止条件为栈s为空,所有元素均已处理完
  4. 访问当前栈顶元素(首先取出栈顶元素,随后pop掉栈顶元素)并存入最终结果
  5. 将右、左节点分别压入栈内,以便取元素时为先左后右。
  6. 返回最终结果

其中步骤4,5,6为迭代的核心,对应前序遍历「根左右」。

所以说到底,使用迭代,只不过是另外一种形式的递归。使用递归的思想去理解遍历问题会容易理解许多。

复杂度分析

使用辅助栈,最坏情况下栈空间与节点数相等,其空间复杂度为 O(n), 对每个节点遍历一次,时间复杂度为 O(n).