Binary Tree Preorder Traversal

描述

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?

分析

用栈或者Morris遍历。

  1. // Binary Tree Preorder Traversal
  2. // 使用栈,时间复杂度O(n),空间复杂度O(n)
  3. class Solution {
  4. public List<Integer> preorderTraversal(TreeNode root) {
  5. ArrayList<Integer> result = new ArrayList<>();
  6. Stack<TreeNode> s = new Stack<>();
  7. if (root != null) s.push(root);
  8. while (!s.isEmpty()) {
  9. final TreeNode p = s.pop();
  10. result.add(p.val);
  11. if (p.right != null) s.push(p.right);
  12. if (p.left != null) s.push(p.left);
  13. }
  14. return result;
  15. }
  16. }

Morris先序遍历

  1. // Binary Tree Preorder Traversal
  2. // Morris先序遍历,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public List preorderTraversal(TreeNode root) {
  5. ArrayList result = new ArrayList<>();
  6. TreeNode cur = root;
  7. TreeNode prev = null;
  8. while (cur != null) {
  9. if (cur.left == null) {
  10. result.add(cur.val);
  11. prev = cur; /* cur刚刚被访问过 */
  12. cur = cur.right;
  13. } else {
  14. /* 查找前驱 */
  15. TreeNode node = cur.left;
  16. while (node.right != null && node.right != cur)
  17. node = node.right;
  18. if (node.right == null) { /* 还没线索化,则建立线索 */
  19. result.add(cur.val); /* 仅这一行的位置与中序不同 */
  20. node.right = cur;
  21. prev = cur; /* cur刚刚被访问过 */
  22. cur = cur.left;
  23. } else { /* 已经线索化,则删除线索 */
  24. node.right = null;
  25. /* prev = cur; 不能有这句,cur已经被访问 */
  26. cur = cur.right;
  27. }
  28. }
  29. }
  30. return result;
  31. }
  32. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/traversal/binary-tree-preorder-traversal.html