题意:

image.png

解题思路:

  1. 思路:
  2. 1. 递归算法:中序遍历过程的顺序是 -> -> 右;
  3. 2. 迭代算法:维护一个栈,把左边的元素全部放入栈中,然后再从栈中弹出元素,再压入右边元素;

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $root
  13. * @return Integer[]
  14. */
  15. public $res = [];
  16. function inorderTraversal($root) {
  17. // return $this->stackInorderTraversal($root);
  18. if ($root) {
  19. $this->inorderTraversal($root->left);
  20. $this->res[] = $root->val;
  21. $this->inorderTraversal($root->right);
  22. }
  23. return $this->res;
  24. }
  25. function stackInorderTraversal($root) {
  26. if ($root == null) return [];
  27. $list = [];
  28. $stack = new SplStack();
  29. while (!$stack->isEmpty() || $root != null) {
  30. while ($root != null) {
  31. $stack->push($root);
  32. $root = $root->left;
  33. }
  34. $root = $stack->pop();
  35. $list[] = $root->val;
  36. $root = $root->right;
  37. }
  38. return $list;
  39. }
  40. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. var res []int
  10. func inorderTraversal(root *TreeNode) []int {
  11. res = make([]int, 0)
  12. dfs(root)
  13. return res
  14. }
  15. func dfs(root *TreeNode) {
  16. if root != nil {
  17. dfs(root.Left)
  18. res = append(res, root.Val)
  19. dfs(root.Right)
  20. }
  21. }
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func inorderTraversal(root *TreeNode) []int {
  10. var res []int
  11. var stack []*TreeNode
  12. for 0 < len(stack) || root != nil {
  13. for root != nil {
  14. stack = append(stack, root)
  15. root = root.Left
  16. }
  17. n := stack[len(stack)-1] // pop
  18. stack = stack[:len(stack)-1]
  19. res = append(res, n.Val)
  20. root = n.Right
  21. }
  22. return res
  23. }