【每日一题】【栈】【递归】【遍历】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 List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); inOrder(root, list); return list; } public void inOrder(TreeNode root, List<Integer> list) { if(root == null) { return; } inOrder(root.left, list); list.add(root.val); inOrder(root.right, list); } } //非递归方式 class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>();
//Deque<TreeNode> stack = new LinkedList<TreeNode>(); //栈非空是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; } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15630511.html