1.迭代实现前序遍历
public List<Integer> preOrderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();if (root == null) {return res;}Deque<TreeNode> stack = new LinkedList<TreeNode>();TreeNode node = root;while (!stack.isEmpty() || node != null) {while (node != null) {res.add(node.val);stack.push(node);node = node.left;}node = stack.pop();node = node.right;}return res;
}
2.迭代实现中序遍历
public List<Integer> inorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();Deque<TreeNode> stack = new LinkedList<TreeNode>();while (root != null || !stack.isEmpty()) {while (root != null) {stack.push(root);root = root.left;}root = stack.pop();res.add(root.val);root = root.right;}return res;
}
3.迭代实现后序遍历(反转法)
将后序遍历的结果反过来就是类似于前序遍历的结果,只不过前序遍历先找左孩子,后序反过来是先找右孩子。
public List<Integer> postOrderTraversal(TreeNode root) {List<Integer> res = new ArrayList<>();if (root == null) {return res;}Deque<TreeNode> stack = new LinkedList<TreeNode>();TreeNode node = root;while (!stack.isEmpty() || node != null) {while (node != null) {res.add(node.val);stack.push(node);node = node.right;}node = stack.pop();node = node.left;}Collections.reverse(res);return res;
}
如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤
个人主页:星不易 ♥
算法通关村专栏:不易|算法通关村 ♥