问题描述
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
解答
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //迭代没想到,先用递归。
/*
这是更简单的迭代
public void inorder(TreeNode root){
if(root == null)return;
inorder(root.left);
list.add(root);
inorder(root.right);
}
*/
//下面是正解
class Solution { public List<Integer> list1; public List<Integer> dfs(TreeNode root){ if(root.left == null && root.right == null){ List<Integer> temp1 = new ArrayList<Integer>(); temp1.add(root.val); return temp1; } List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); if(root.left!=null)left = dfs(root.left); if(root.right!=null)right = dfs(root.right); List<Integer> center = new ArrayList<Integer>(); center.add(root.val); left.addAll(center); left.addAll(right); return left; } public List<Integer> inorderTraversal(TreeNode root) { if(root==null)return new ArrayList<Integer>(); list1 = dfs(root); return list1; } }