leetcode94 二叉树的中序遍历
【摘要】
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3
输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归
/** * D...
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归
-
/**
-
* Definition for a binary tree node.
-
* public class TreeNode {
-
* int val;
-
* TreeNode left;
-
* TreeNode right;
-
* TreeNode(int x) { val = x; }
-
* }
-
*/
-
class Solution {
-
public List < Integer > inorderTraversal(TreeNode root) {
-
List < Integer > res = new ArrayList < > ();
-
helper(root, res);
-
return res;
-
}
-
public void helper(TreeNode root, List < Integer > res) {
-
if(root == null)return;
-
helper(root.left, res);
-
res.add(root.val);
-
helper(root.right, res);
-
}
-
}
压栈
-
public class Solution {
-
public List < Integer > inorderTraversal(TreeNode root) {
-
List < Integer > res = new ArrayList < > ();
-
Stack < TreeNode > stack = new Stack < > ();
-
TreeNode curr = root;
-
while (curr != null || !stack.isEmpty()) {
-
while (curr != null) {
-
stack.push(curr);
-
curr = curr.left;
-
}
-
curr = stack.pop();
-
res.add(curr.val);
-
curr = curr.right;
-
}
-
return res;
-
}
-
}
morris
虽然是空间O(1),但是oj并没有测出来效果,依旧空间只超过40%
-
/**
-
* Definition for a binary tree node.
-
* public class TreeNode {
-
* int val;
-
* TreeNode left;
-
* TreeNode right;
-
* TreeNode(int x) { val = x; }
-
* }
-
*/
-
class Solution {
-
public List < Integer > inorderTraversal(TreeNode root) {
-
List < Integer > res = new ArrayList < > ();
-
TreeNode curr = root;
-
TreeNode pre;
-
while (curr != null) {
-
if (curr.left == null) {
-
res.add(curr.val);
-
curr = curr.right; // move to next right node
-
} else { // has a left subtree
-
pre = curr.left;
-
while (pre.right != null) { // find rightmost
-
pre = pre.right;
-
}
-
pre.right = curr; // put cur after the pre node
-
TreeNode temp = curr; // store cur node
-
curr = curr.left; // move cur to the top of the new tree
-
temp.left = null; // original cur left be null, avoid infinite loops
-
}
-
}
-
return res;
-
}
-
}
文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。
原文链接:fantianzuo.blog.csdn.net/article/details/103299465
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)