题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
解题思路:
方法一:递归
中序遍历的操作定义为,若二叉树为空,则空操作,否则:
AC代码
/**
* 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 inorderTraversal(TreeNode root) {
List result = new ArrayList<>();
process(result,root);
return result;
}
public void process(List result ,TreeNode root){
if (root==null){
return;
}
//中序遍历左子树
process(result,root.left);
//访问根节点
result.add(root.val);
//中序遍历右子树
process(result,root.right);
}
}
方法二:迭代,递归的循环版本,借助栈来完成递归,
如果root !=null 或者 stack的大小不为0,则循环执行:
/**
* 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 inorderTraversal(TreeNode root) {
List result = new ArrayList<>();
Deque stack = new LinkedList<>();
while (root!=null||!stack.isEmpty()){
//遍历左子树
while (root!=null){
stack.push(root);
root=root.left;
}
root = stack.pop();
//访问根节点
result.add(root.val);
//遍历右子树
root=root.right;
}
return result;
}
}