题目地址:https://leetcode.com/problems/binary-tree-inorder-traversal/description/
思路:二叉树的中序遍历
AC代码(非递归实现)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> nodes = new Stack<>();
List<Integer> vals = new ArrayList<>();
while (root != null || !nodes.isEmpty()) {
while (root != null) {
nodes.push(root);
root = root.left;
}
// 返回值同时删除
root = nodes.pop();
vals.add(root.val);
root = root.right;
}
return vals;
}
}
AC代码(递归实现)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> vals = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root != null) {
if (root.left != null) {
this.inorderTraversal(root.left);
}
vals.add(root.val);
if (root.right != null) {
this.inorderTraversal(root.right);
}
}
return vals;
}
}