赞
踩
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[2,1]
示例 5:
输入:root = [1,null,2] 输出:[1,2]
提示:
[0, 100] 内-100 <= Node.val <= 100
递归很简单粗暴,还是迭代好
package com.example.suanfa; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class three { } class Solution { public List<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> res = new ArrayList<>(); LinkedList<TreeNode> tn = new LinkedList<>(); while (root != null || !tn.isEmpty()){ while (root != null) { tn.push(root); root = root.left; } root = tn.pop(); res.add(root.val); root = root.right; } return res; } } 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; } }
网上还有其他解法,如颜色标记法,莫里斯遍历。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。