【LeetCode】【HOT】94. 二叉树的中序遍历
package hot; import java.util.ArrayList; import java.util.List; class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int val){ this.val = val; } } public class Solution94 { public static void main(String[] args) { TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); node1.right = node2; node2.left = node3; Solution94 solution = new Solution94(); System.out.println(solution.method(node1)); } private Listmethod(TreeNode root){ List res = new ArrayList<>(); TreeNode predecessor = null; while(root != null){ if(root.left != null){ predecessor = root.left; while(predecessor.right != null && predecessor.right != root){ predecessor = predecessor.right; } if(predecessor.right == null){ predecessor.right = root; root = root.left; }else{ res.add(root.val); predecessor.right = null; root = root.right; } }else{ res.add(root.val); root = root.right; } } return res; } } //时间复杂度为 O(n) //空间复杂度为 O(1)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)