LeetCode 94 二叉树的中序遍历 题解
给定一个二叉树,返回它的中序 遍历。
方法:递归、迭代(栈)、Morris 中序遍历
递归和迭代:
时间复杂度:O(n),其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。
空间复杂度:O(n)。空间复杂度取决于(递归或者迭代)栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别。
Morris:
时间复杂度:O(n),其中 n 为二叉搜索树的节点个数。Morris 遍历中每个节点会被访问两次,因此总时间复杂度为 O(2n)=O(n)。
空间复杂度:O(1)。
/**
* 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> list=new ArrayList<>();
if(root==null){
return list;
}
midOder(list,root);
return list;
}
public void midOder( List<Integer> list,TreeNode root){
if(root.left!=null){//这样会节省一次函数调用
midOder(list,root.left);
}
list.add(root.val);
if(root.right!=null){
midOder(list,root.right);
}
return;
}
public List<Integer> inorderTraversal2(TreeNode root) {
List<Integer> list=new ArrayList<>();
if(root==null){
return list;
}
Deque<TreeNode> queue=new ArrayDeque<>();
while(root!=null||!queue.isEmpty()){
while(root!=null){
queue.push(root);
root=root.left;
}
root=queue.pop();
list.add(root.val);
root=root.right;
}
return list;
}
}
/**
* 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> list=new ArrayList<>();
if(root==null){
return list;
}
TreeNode predecessor=null;
while(root!=null){
if(root.left!=null){
// predecessor 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止
predecessor=root.left;
while(predecessor.right!=null&&predecessor.right!=root){
predecessor=predecessor.right;
}
// predecessor 右孩子为空,则使其右指针指向 root,继续遍历左子树
if(predecessor.right==null){
predecessor.right=root;
root=root.left;
}
// predecessor 右孩子不为空[此时应该是右孩子为root],说明已经遍历完了左子树;断开predecessor和root的链接
else{
list.add(root.val);
root=root.right;
predecessor.right=null;
}
}
//没有左孩子
else{
list.add(root.val);
root=root.right;
}
}
return list;
}
}