题目链接:https://leetcode.com/problems/binary-tree-inorder-traversal/
1. 题目介绍(Binary Tree Inorder Traversal)
Given the root of a binary tree, return the inorder traversal of its nodes’ values.
【Translate】: 给定二叉树的根,返回其节点值的中序遍历。
【测试用例】:
【条件约束】:
【跟踪】:
Follow up: Recursive solution is trivial, could you do it iteratively?
【Translate】: 递归求解很简单,你能迭代求解吗
2. 题解
这个题就没什么好讲的了, 属于数据结构的基础,即 左-root-右.
2.1 递归
/**
* 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> res = new ArrayList<>();
inorder(root, res);
return res;
}
/**
* 递归三步骤、
* 1. 确定递归函数的参数和返回值;
* 2. 确定终止条件;
* 3. 确定单层递归的逻辑
*/
private void inorder(TreeNode root, List<Integer> res) {
if(root == null){
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
or
/**
* 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;
}
}
2.2 栈
程序解释流程图来自于 YaoFrankie 在 Iterative solution in Java - simple and readable 中的comment.
/**
* 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) {
TreeNode node = root;
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (node != null || !stack.empty()){
while (node != null){
stack.push(node);
node = node.left;
}
node = stack.pop();
list.add(node.val);
node = node.right;
}
return list;
}
}
3. 参考资料
[1] 前序遍历 (preorder traversal) - 中序遍历 (inorder traversal) - 后序遍历 (postorder traversal) | CSDN
[2] Java实现二叉树的递归遍历(前序遍历、中序遍历、后序遍历) | CSDN