题目大意

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

94. Binary Tree Inorder Traversal

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?

解题思路

中序遍历:左根右

Approach 1: Recursive Approach 递归

The first method to solve this problem is using recursion. This is the classical method and is straightforward. We can define a helper function to implement recursion.

Python解法

class Solution(object):
def inorderTraversal(self, root): # 递归
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)

Java解法

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) {
if (root.left != null) {
helper(root.left, res);
}
res.add(root.val);
if (root.right != null) {
helper(root.right, res);
}
}
}
}

Complexity Analysis

Time complexity : O(n)O(n). The time complexity is O(n)O(n) because the recursive function is T(n) = 2 \cdot T(n/2)+1T(n)=2⋅T(n/2)+1.

Space complexity : The worst case space required is O(n)O(n), and in the average case it's O(log(n))O(log(n)) where nn is number of nodes.

Approach 2: Iterating method using Stack 迭代(基于栈)

The strategy is very similiar to the first method, the different is using stack.

伪代码如下(摘录自Wikipedia Tree_traversal)

iterativeInorder(node)
parentStack = empty stack
while (not parentStack.isEmpty() or node ≠ null)
if (node ≠ null)
parentStack.push(node)
node = node.left
else
node = parentStack.pop()
visit(node)
node = node.right

Python解法

class Solution(object):
def inorderTraversal(self, root): # 迭代
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
res = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.val)
root = root.right
return res

Java解法

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;
}
}

Complexity Analysis

Time complexity : O(n)O(n).

Space complexity : O(n)O(n).

Approach 3: Morris Traversal

In this method, we have to use a new data structure-Threaded Binary Tree, and the strategy is as follows:

Step 1: Initialize current as root

Step 2: While current is not NULL,

If current does not have left child

    a. Add current’s value

    b. Go to the right, i.e., current = current.right

Else

    a. In current's left subtree, make current the right child of the rightmost node

    b. Go to this left child, i.e., current = current.left

For example:

          1
/ \
2 3
/ \ /
4 5 6

First, 1 is the root, so initialize 1 as current, 1 has left child which is 2, the current's left subtree is

         2
/ \
4 5

So in this subtree, the rightmost node is 5, then make the current(1) as the right child of 5. Set current = cuurent.left (current = 2). The tree now looks like:

         2
/ \
4 5
\
1
\
3
/
6

For current 2, which has left child 4, we can continue with thesame process as we did above

        4
\
2
\
5
\
1
\
3
/
6

then add 4 because it has no left child, then add 2, 5, 1, 3 one by one, for node 3 which has left child 6, do the same as above. Finally, the inorder taversal is [4,2,5,1,6,3].

For more details, please check Threaded binary tree and Explaination of Morris Method

Python解法

class Solution(object):
def inorderTraversal(self, root): # Morris Traversal
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
curr, pre = root, None
while curr:
if curr.left:
pre = curr.left
while pre.right:
pre = pre.right
pre.right = curr
curr.left, curr = None, curr.left
else:
res.append(curr.val)
curr = curr.right
return res

Java解法

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;
}
}

Complexity Analysis

Time complexity : O(n)O(n). To prove that the time complexity is O(n)O(n), the biggest problem lies in finding the time complexity of finding the predecessor nodes of all the nodes in the binary tree. Intuitively, the complexity is O(nlogn)O(nlogn), because to find the predecessor node for a single node related to the height of the tree. But in fact, finding the predecessor nodes for all nodes only needs O(n)O(n) time. Because a binary Tree with nn nodes has n-1n−1 edges, the whole processing for each edges up to 2 times, one is to locate a node, and the other is to find the predecessor node. So the complexity is O(n)O(n).

Space complexity : O(n)O(n). Arraylist of size nn is used.

参考:

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

http://bookshadow.com/weblog/2015/01/19/leetcode-binary-tree-inorder-traversal/

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

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

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

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

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

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

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

  4. [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历

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

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

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

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

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

  7. Leetcode 94 Binary Tree Inorder Traversal 二叉树

    二叉树的中序遍历,即左子树,根, 右子树 /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *lef ...

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

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

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

    Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [1,null,2,3] ...

随机推荐

  1. codevs 1081 线段树练习 2 线段树

    题目描述 Description 给你N个数,有两种操作 1:给区间[a,b]的所有数都增加X 2:询问第i个数是什么? 输入描述 Input Description 第一行一个正整数n,接下来n行n ...

  2. Springboot 如何加密,以及利用Swagger2构建Restful API

    先看一下使用Swagger2构建Restful API效果图 超级简单的,只需要在pom 中引用如下jar包 <dependency> <groupId>io.springfo ...

  3. TeamViewer 说明截图

  4. Win7下怎么设置让远程桌面连接记住密码下次登录不需再输入

    远程桌面连接功能想必大家都不会陌生吧,特别是使用VPS服务器的用户们经常会用到,为了服务器的安全每次都会把密码设置的很复制,但是这样也有一个麻烦,就是每次要桌面远程连接的时候都要输入这么复杂的密码,很 ...

  5. HDU 1540 Tunnel Warfare

    HDU 1540 思路1: 树状数组+二分 代码: #include<bits/stdc++.h> using namespace std; #define ll long long #d ...

  6. Unity中使用的一套敏感词过滤方式

    当项目中的敏感词数量不是很多的时候,直接用数组来遍历过滤其实也可以,但是具体的数量有多大,这个肯定不好说,因此,对.txt中的敏感词合理组织后再进行过滤就显得非常有必要了. 如上图,左边是txt中配置 ...

  7. Python map/reduce

    2017-07-31 18:20:59 一.map函数 map():会根据提供的函数对指定序列做映射.第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 ...

  8. Matlab scatter 如何显示不同颜色点状

    有时候需要在matlab scatter绘图中显示不同颜色区分,如下图是人体血压高压.低压与年龄关系的散点图. 红色点表示高压 绿色点表示低压 用 matlab 如何实现呢? 1.创建一维矩阵x,y1 ...

  9. python-day9-数据类型总结

    数据类型总结: 常用:  数字 字符串 列表 元组 字典 不常用:集合 1.按照存值个数: 1个:数字,字符串 多个:列表,元组,字典,(集合) 2.按照可变不可变: 可变:列表,字典,(集合) 不可 ...

  10. Linux的fork()写时复制原则(转)

    写时复制技术最初产生于Unix系统,用于实现一种傻瓜式的进程创建:当发出fork(  )系统调用时,内核原样复制父进程的整个地址空间并把复制的那一份分配给子进程.这种行为是非常耗时的,因为它需要: · ...