Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1
\
2
/
3 Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

二叉树的中序遍历顺序为左-根-右,可以有递归和非递归来解,其中非递归解法又分为两种,一种是使用栈来接,另一种不需要使用栈。我们先来看递归方法,十分直接,对左子结点调用递归函数,根节点访问值,右子节点再调用递归函数,代码如下:

解法一:

class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
inorder(root, res);
return res;
}
void inorder(TreeNode *root, vector<int> &res) {
if (!root) return;
if (root->left) inorder(root->left, res);
res.push_back(root->val);
if (root->right) inorder(root->right, res);
}
};

下面再来看非递归使用栈的解法,也是符合本题要求使用的解法之一,需要用栈来做,思路是从根节点开始,先将根节点压入栈,然后再将其所有左子结点压入栈,然后取出栈顶节点,保存节点值,再将当前指针移到其右子节点上,若存在右子节点,则在下次循环时又可将其所有左子结点压入栈中。这样就保证了访问顺序为左-根-右,代码如下:

解法二:

// Non-recursion
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode *p = root;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
res.push_back(p->val);
p = p->right;
}
return res;
}
};

下面这种解法跟 Binary Tree Preorder Traversal 中的解法二几乎一样,就是把结点值加入结果 res 的步骤从 if 中移动到了 else 中,因为中序遍历的顺序是左-根-右,参见代码如下:

解法三:

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode *p = root;
while (!s.empty() || p) {
if (p) {
s.push(p);
p = p->left;
} else {
p = s.top(); s.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};

下面来看另一种很巧妙的解法,这种方法不需要使用栈,所以空间复杂度为常量,这种非递归不用栈的遍历方法有个专门的名字,叫 Morris Traversal,在介绍这种方法之前,先来引入一种新型树,叫 Threaded binary tree,这个还不太好翻译,第一眼看上去以为是叫线程二叉树,但是感觉好像又跟线程没啥关系,后来看到网上有人翻译为螺纹二叉树,但博主认为这翻译也不太敢直视,很容易让人联想到为计划生育做出突出贡献的某世界著名品牌,后经热心网友提醒,应该叫做线索二叉树。先来看看维基百科上关于它的英文定义:

A binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node (if it exists), and all left child pointers that would normally be null point to the inorder predecessor of the node.

就是说线索二叉树实际上是把所有原本为空的右子节点指向了中序遍历顺序之后的那个节点,把所有原本为空的左子节点都指向了中序遍历之前的那个节点,具体例子可以点击这里。那么这道题跟这个线索二叉树又有啥关系呢?由于既不能用递归,又不能用栈,那如何保证访问顺序是中序遍历的左-根-右呢。原来需要构建一个线索二叉树,需要将所有为空的右子节点指向中序遍历的下一个节点,这样中序遍历完左子结点后,就能顺利的回到其根节点继续遍历了。具体算法如下:

1. 初始化指针 cur 指向 root

2. 当 cur 不为空时

  - 如果 cur 没有左子结点

      a) 打印出 cur 的值

    b) 将 cur 指针指向其右子节点

  - 反之

     将 pre 指针指向 cur 的左子树中的最右子节点 

     * 若 pre 不存在右子节点

          a) 将其右子节点指回 cur

        b) cur 指向其左子节点

     * 反之

      a) 将 pre 的右子节点置空

      b) 打印 cur 的值

      c) 将 cur 指针指向其右子节点

解法四:

class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
if (!root) return res;
TreeNode *cur, *pre;
cur = root;
while (cur) {
if (!cur->left) {
res.push_back(cur->val);
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur) pre = pre->right;
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = NULL;
res.push_back(cur->val);
cur = cur->right;
}
}
}
return res;
}
};

其实 Morris 遍历不仅仅对中序遍历有用,对先序和后序同样有用,具体可参见网友 NOALGO 博客,和 Annie Kim's Blog 的博客。所以对二叉树的三种常见遍历顺序(先序,中序,后序)就有三种解法(递归,非递归,Morris 遍历),总共有九段代码呀,熟练掌握这九种写法才算初步掌握了树的遍历挖~~ 至于二叉树的层序遍历也有递归和非递归解法,至于有没有 Morris 遍历的解法还有待大神们的解答,若真有也请劳烦告知博主一声~~

Github 同步地址:

https://github.com/grandyang/leetcode/issues/94

类似题目:

Validate Binary Search Tree

Binary Tree Preorder Traversal

Binary Tree Postorder Traversal

Binary Search Tree Iterator

Kth Smallest Element in a BST

Closest Binary Search Tree Value II

Inorder Successor in BST

参考资料:

https://leetcode.com/problems/binary-tree-inorder-traversal/

https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/31231/c-ierative-recursive-and-morris-traversal

https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/31213/iterative-solution-in-java-simple-and-readable

https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45551/preorder-inorder-and-postorder-iteratively-summarization

https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45621/preorder-inorder-and-postorder-traversal-iterative-java-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历的更多相关文章

  1. [leetcode] 94. Binary Tree Inorder Traversal 二叉树的中序遍历

    题目大意 https://leetcode.com/problems/binary-tree-inorder-traversal/description/ 94. Binary Tree Inorde ...

  2. LeetCode 94. Binary Tree Inorder Traversal 二叉树的中序遍历 C++

    Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [,,] \ / Out ...

  3. 【LeetCode】Binary Tree Inorder Traversal(二叉树的中序遍历)

    这道题是LeetCode里的第94道题. 题目要求: 给定一个二叉树,返回它的中序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单 ...

  4. Leetcode94. Binary Tree Inorder Traversal二叉树的中序遍历(两种算法)

    给定一个二叉树,返回它的中序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 递归: class So ...

  5. [LeetCode] 94. Binary Tree Inorder Traversal(二叉树的中序遍历) ☆☆☆

    二叉树遍历(前序.中序.后序.层次.深度优先.广度优先遍历) 描述 解析 递归方案 很简单,先左孩子,输出根,再右孩子. 非递归方案 因为访问左孩子后要访问右孩子,所以需要栈这样的数据结构. 1.指针 ...

  6. [LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历

    Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary ...

  7. [LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  8. [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  9. [Leetcode] Binary tree inorder traversal二叉树中序遍历

    Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary tre ...

随机推荐

  1. CloudNotes之桌面客户端篇:笔记撰写样式的支持

    最近在CloudNotes桌面客户端中新增了笔记撰写样式的功能.当用户新建笔记的时候,可以在输入笔记标题的同时,选择笔记撰写样式,由安装包默认提供的样式主要有默认样式(Default).羊皮纸样式(L ...

  2. C# WinForm国际化的简单实现

    软件行业发展到今天,国际化问题一直都占据非常重要的位置,而且应该越来越被重视.对于开发人员而言,在编写程序之前,国际化问题是首先要考虑的一个问题,也许有时候这个问题已经在设计者的考虑范围之内,但终归要 ...

  3. csharp: Download SVN source

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  4. git push不用重复输入用户名和密码(解决方案)

    每次git push都要输入用户名和密码,有点麻烦,就上网搜了下解决方案. 网上的解决方案有的讲得不清晰,逐个试了后,总结下两种有效的解决方案.   方案一: 1.在计算机安装盘(即一般为C盘)下找到 ...

  5. python 学习笔记 -logging模块(日志)

    模块级函数 logging.getLogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug().logging.info().lo ...

  6. 9.2.4 .net core 通过ViewComponent封装控件

    我们在.net core中还使用了ViewComponent方式生成控件.ViewComponent也是asp.net core的新特性,是对页面部分的渲染,以前PartialView的功能,可以使用 ...

  7. 【HTML5&CSS3进阶04】CSS3动画应该如何在webapp中运用

    动画在webapp的现状 webapp模式的网站追求的就是一个体验,是HTML5&CSS3浪潮下的产物,抛开体验不说,webapp模式门槛比较高: 而体验优化的一个重点便是动画,可以说动画是w ...

  8. Unicode简介

    计算机只能处理二进制,因此需要把文字表示为二进制才能被计算机理解和识别. 一般的做法是为每一个字母或汉字分配一个id,然后用二进制表示这个id,存在内存或磁盘中.计算机可以根据二进制数据知道这个id是 ...

  9. React Native知识12-与原生交互

    一:原生传递参数给React Native 1:原生给React Native传参 原生给JS传数据,主要依靠属性. 通过initialProperties,这个RCTRootView的初始化函数的参 ...

  10. Android Xfermode 学习笔记

    一.概述 Xfermode全名transfer-mode,其作用是实现两张图叠加时的混合效果. 网上流传的关于Xfermode最出名的图来源于AndroidSDK的samples中,名叫Xfermod ...