Binary Tree Inorder Traversal

Question

Problem Statement

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

Example

Given binary tree {1,#,2,3},

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

return [1,3,2].

Challenge

Can you do it without recursion?

題解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 這種動態語言在寫遞迴時返回結果好處理點,無需聲明類型。通用的方法爲在遞迴函數入口參數中傳入返回結果,
也可使用分治的方法替代輔助函數。

複雜度分析

樹中每個節點都需要被訪問常數次,時間複雜度近似爲 O(n). 未使用額外輔助空間。

題解2 - 迭代版

使用輔助 stack 改寫遞迴程序,中序遍歷沒有前序遍歷好寫,其中之一就在於出入 stack 的順序和限制規則。我們採用「左根右」的訪問順序可知主要由如下四步構成。

  1. 首先需要一直對左子樹迭代並將非空節點壓入 stack
  2. 節點指針爲空後不再壓入 stack
  3. 當前節點爲空時進行出 stack 操作,並訪問 stack 頂節點
  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. if (root == null) return result;
  14. Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
  15. while (root != null || (!stack.isEmpty())) {
  16. if (root != null) {
  17. stack.push(root);
  18. root = root.left;
  19. } else {
  20. root = stack.pop();
  21. result.add(root.val);
  22. root = root.right;
  23. }
  24. }
  25. return result;
  26. }
  27. }

源碼分析

使用 stack 的思想模擬遞迴,注意迭代的演進和邊界條件即可。

複雜度分析

最壞情況下 stack 保存所有節點,空間複雜度 O(n), 時間複雜度 O(n).

Reference