题目地址
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
题目描述
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [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() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> results = new ArrayList<>();
traverse(root, results);
return results;
}
public void traverse(TreeNode root, List<Integer> results) {
if (root == null) return;
traverse(root.left, results);
// 中序遍历
results.add(root.val);
traverse(root.right, results);
}
}
迭代解法
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<> ();
Stack<TreeNode> stack = new Stack<> ();
while (root != null || !stack.isEmpty()) {
// 左子树入栈
while (root != null) {
stack.push(root);
root = root.left;
}
// 中序遍历
root = stack.pop();
res.add(root.val);
// 遍历右子树
root = root.right;
}
return res;
}
}