/*中序遍历*/
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<>(); Deque<TreeNode> stack=new LinkedList<>(); 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; } }
/*前序遍历*/
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<>(); Deque<TreeNode> stack=new LinkedList<>(); while(!stack.isEmpty() || root!=null){ while(root!=null){ list.add(root.val); stack.push(root); root=root.left; } root=stack.pop(); root=root.right; } return list; } }
/*后序遍历*/
class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } Deque<TreeNode> stack = new LinkedList<TreeNode>(); TreeNode prev = null; while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if (root.right == null || root.right == prev) { res.add(root.val); prev = root; root = null; } else { stack.push(root); root = root.right; } } return res; } }
标签:遍历,迭代,list,List,new,null,root,stack From: https://www.cnblogs.com/ztzzh-1/p/17679033.html