94.二叉树的中序遍历 给定一个二叉树的根节点 root
,返回它的 中序 遍历。
示例 1:
1 2 输入:root = [1,null,2,3] 输出:[1,3,2]
Solution :递归
1 2 3 4 5 6 7 8 9 10 11 12 class Solution { ArrayList<Integer> list=new ArrayList <>(); public List<Integer> inorderTraversal (TreeNode root) { if (root==null ){ return list; } inorderTraversal(root.left); list.add(root.val); inorderTraversal(root.right); return list; } }
tips:逆中序遍历:右—->根—->左
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { public void reverseInorder (TreeNode root) { if (root == null ) { return ; } reverseInorder(root.right); System.out.print(root.val + " " ); reverseInorder(root.left); } }
Solution1 : 栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution { public List<Integer> inorderTraversal (TreeNode root) { List<Integer> res = new ArrayList<Integer>(); Deque<TreeNode> stk = new LinkedList<TreeNode>(); while (root != null || !stk.isEmpty()) { while (root != null ) { stk.push(root); root = root.left; } root = stk.pop(); res.add(root.val); root = root.right; } return res; } }