leetcode94 二叉树的中序遍历

举报
兔老大 发表于 2021/04/25 23:53:07 2021/04/25
【摘要】 给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3]    1     \      2     /    3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 递归 /** * D...

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

递归


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

压栈


  
  1. public class Solution {
  2. public List < Integer > inorderTraversal(TreeNode root) {
  3. List < Integer > res = new ArrayList < > ();
  4. Stack < TreeNode > stack = new Stack < > ();
  5. TreeNode curr = root;
  6. while (curr != null || !stack.isEmpty()) {
  7. while (curr != null) {
  8. stack.push(curr);
  9. curr = curr.left;
  10. }
  11. curr = stack.pop();
  12. res.add(curr.val);
  13. curr = curr.right;
  14. }
  15. return res;
  16. }
  17. }

morris

虽然是空间O(1),但是oj并没有测出来效果,依旧空间只超过40%


  
  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. class Solution {
  11. public List < Integer > inorderTraversal(TreeNode root) {
  12. List < Integer > res = new ArrayList < > ();
  13. TreeNode curr = root;
  14. TreeNode pre;
  15. while (curr != null) {
  16. if (curr.left == null) {
  17. res.add(curr.val);
  18. curr = curr.right; // move to next right node
  19. } else { // has a left subtree
  20. pre = curr.left;
  21. while (pre.right != null) { // find rightmost
  22. pre = pre.right;
  23. }
  24. pre.right = curr; // put cur after the pre node
  25. TreeNode temp = curr; // store cur node
  26. curr = curr.left; // move cur to the top of the new tree
  27. temp.left = null; // original cur left be null, avoid infinite loops
  28. }
  29. }
  30. return res;
  31. }
  32. }

 

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/103299465

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。