# 题目
给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3] | |
输出:[1,3,2] |
示例二:
输入:root = [] | |
输出:[] |
示例 3:
输入:root = [1]
输出:[1]
tips:
- 树中节点数目在范围
[0, 100]
内 -100 <= Node.val <= 100
# 解法一:使用递归
记忆:中序遍历不忘 “左链入栈”
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode() {} | |
* TreeNode(int val) { this.val = val; } | |
* TreeNode(int val, TreeNode left, TreeNode right) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
class Solution { | |
List<Integer> list = new ArrayList<>(); | |
public List<Integer> inorderTraversal(TreeNode root) { | |
if(root != null){ | |
inorderTraversal(root.left); | |
list.add(root.val); | |
inorderTraversal(root.right); | |
} | |
return list; | |
} | |
} |
# 解法二:使用栈
class Solution { | |
public List<Integer> inorderTraversal(TreeNode root) { | |
List<Integer> list = new ArrayList<>(); | |
Stack<TreeNode> stack = new Stack<>(); | |
TreeNode cur = root; | |
while (cur != null || !stack.isEmpty()) { | |
if (cur != null) { | |
stack.push(cur); | |
cur = cur.left; | |
} else { | |
cur = stack.pop(); | |
list.add(cur.val); | |
cur = cur.right; | |
} | |
} | |
return list; | |
} | |
} |