题意:

image.png

解题思路:

  1. 思路:
  2. 1.从根节点出发,先将根节点存入栈中;
  3. 2.每次迭代弹出当前栈顶元素,并将其孩子节点压入栈中;
  4. 3.先压入右孩子,再压入左孩子,为的是先弹出左孩子的值[左孩子在栈顶端];

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 preorderTraversal($root) {
  17. return $this->stackPreorderTraversal($root);
  18. if ($root) {
  19. $this->res[] = $root->val;
  20. $this->preorderTraversal($root->left);
  21. $this->preorderTraversal($root->right);
  22. }
  23. return $this->res;
  24. }
  25. function stackPreorderTraversal($root) {
  26. if ($root == null) return [];
  27. $list = [];
  28. $stack = new SplStack();
  29. $stack->push($root);
  30. while (!$stack->isEmpty()) {
  31. $root = $stack->pop();
  32. $list[] = $root->val;
  33. if ($root->right != null) $stack->push($root->right);
  34. if ($root->left != null) $stack->push($root->left);
  35. }
  36. return $list;
  37. }
  38. }

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 preorderTraversal(root *TreeNode) []int {
  11. return stackPreOrderTraversal(root)
  12. res = []int{}
  13. dfs(root)
  14. return res
  15. }
  16. func dfs(root *TreeNode) {
  17. if root != nil {
  18. res = append(res, root.Val)
  19. dfs(root.Left)
  20. dfs(root.Right)
  21. }
  22. }
  23. func stackPreOrderTraversal(root *TreeNode) []int {
  24. if root == nil {
  25. return nil
  26. }
  27. var stack []*TreeNode
  28. stack = append(stack, root)
  29. var res []int
  30. for len(stack) > 0 {
  31. p := stack[len(stack) - 1]
  32. stack = stack[0 : len(stack) - 1]
  33. res = append(res, p.Val)
  34. if p.Right != nil {
  35. stack = append(stack, p.Right)
  36. }
  37. if p.Left != nil {
  38. stack = append(stack, p.Left)
  39. }
  40. }
  41. return res
  42. }