Binary Tree Inorder Traversal

Tags: Tree, Hash Table, Stack, Medium

Question

Problem Statement

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

For example:
Given binary tree [1,null,2,3],

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

return [1,3,2].

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

题解1 - 递归版

中序遍历的访问顺序为『先左再根后右』,递归版最好理解,递归调用时注意返回值和递归左右子树的顺序即可。

Python

  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: Inorder in ArrayList which contains node values.
  12. """
  13. def inorderTraversal(self, root):
  14. if root is None:
  15. return []
  16. else:
  17. return [root.val] + self.inorderTraversal(root.left) \
  18. + self.inorderTraversal(root.right)

Python - with helper

  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 inorderTraversal(self, root):
  11. result = []
  12. self.helper(root, result)
  13. return result
  14. def helper(self, root, ret):
  15. if root is not None:
  16. self.helper(root.left, ret)
  17. ret.append(root.val)
  18. self.helper(root.right, ret)

C++

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<int> inorderTraversal(TreeNode* root) {
  13. vector<int> result;
  14. helper(root, result);
  15. return result;
  16. }
  17. private:
  18. void helper(TreeNode *root, vector<int> &ret) {
  19. if (root != NULL) {
  20. helper(root->left, ret);
  21. ret.push_back(root->val);
  22. helper(root->right, ret);
  23. }
  24. }
  25. };

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> inorderTraversal(TreeNode root) {
  12. List<Integer> result = new ArrayList<Integer>();
  13. helper(root, result);
  14. return result;
  15. }
  16. private void helper(TreeNode root, List<Integer> ret) {
  17. if (root != null) {
  18. helper(root.left, ret);
  19. ret.add(root.val);
  20. helper(root.right, ret);
  21. }
  22. }
  23. }

源码分析

Python 这种动态语言在写递归时返回结果好处理点,无需声明类型。通用的方法为在递归函数入口参数中传入返回结果,
也可使用分治的方法替代辅助函数。Java 中 helper 的输入参数中 ret 不能和 inorderTraversal 中的 result 一样。

复杂度分析

树中每个节点都需要被访问常数次,时间复杂度近似为 O(n). 未使用额外辅助空间。

题解2 - 迭代版

使用辅助栈改写递归程序,中序遍历没有前序遍历好写,其中之一就在于入栈出栈的顺序和限制规则。我们采用「左根右」的访问顺序可知主要由如下四步构成。

  1. 首先需要一直对左子树迭代并将非空节点入栈
  2. 节点指针为空后不再入栈
  3. 当前节点为空时进行出栈操作,并访问栈顶节点
  4. 将当前指针p用其右子节点替代

步骤2,3,4对应「左根右」的遍历结构,只是此时的步骤2取的左值为空。

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 inorderTraversal(self, root):
  11. result = []
  12. s = []
  13. while root is not None or s:
  14. if root is not None:
  15. s.append(root)
  16. root = root.left
  17. else:
  18. root = s.pop()
  19. result.append(root.val)
  20. root = root.right
  21. 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. /**
  15. * @param root: The root of binary tree.
  16. * @return: Inorder in vector which contains node values.
  17. */
  18. public:
  19. vector<int> inorderTraversal(TreeNode *root) {
  20. vector<int> result;
  21. stack<TreeNode *> s;
  22. while (!s.empty() || NULL != root) {
  23. if (root != NULL) {
  24. s.push(root);
  25. root = root->left;
  26. } else {
  27. root = s.top();
  28. s.pop();
  29. result.push_back(root->val);
  30. root = root->right;
  31. }
  32. }
  33. return result;
  34. }
  35. };

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> inorderTraversal(TreeNode root) {
  12. List<Integer> result = new ArrayList<Integer>();
  13. Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
  14. TreeNode curr = root;
  15. while (curr != null || !stack.isEmpty()) {
  16. if (curr != null) {
  17. stack.push(curr);
  18. curr = curr.left;
  19. } else {
  20. curr = stack.pop();
  21. result.add(curr.val);
  22. curr = curr.right;
  23. }
  24. }
  25. return result;
  26. }
  27. }

源码分析

使用栈的思想模拟递归,注意迭代的演进和边界条件即可。Java 中新建变量 curr 而不是复用 root 观察下来有一点性能提升。

复杂度分析

最坏情况下栈保存所有节点,空间复杂度 O(n), 时间复杂度 O(n).

Reference