【每日一题】【栈】【递归】【遍历】2021年12月1日-94. 二叉树的中序遍历
TreeNode给定一个二叉树的根节点 root
,返回它的 中序 遍历。
两种方式:递归(先序后序也要掌握)或非递归
/** * 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 ListinorderTraversal(TreeNode root) { List list = new ArrayList<>(); inOrder(root, list); return list; } public void inOrder(TreeNode root, List list) { if(root == null) { return; } inOrder(root.left, list); list.add(root.val); inOrder(root.right, list); } } //非递归方式 class Solution { public List inorderTraversal(TreeNode root) { List list = new ArrayList<>(); Stack stack = new Stack<>();
//Dequestack = new LinkedList //栈非空是isEmpty()而不是!=null while(root != null || !stack.isEmpty()) { while(root != null) { stack.push(root); root = root.left; } root = stack.pop(); list.add(root.val); root = root.right; } return list; } }();