二叉树的迭代遍历
一般的迭代遍历比较难理解,今天看到了一种“通法”。
package com.klaus.prob94;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
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;
}
}
public class Solution {
List<Integer> res = new ArrayList<>();
class Node {
TreeNode treeNode;
boolean flag;
public Node(TreeNode treeNode, boolean flag) {
this.treeNode = treeNode;
this.flag = flag;
}
}
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return res;
LinkedList<Node> stack = new LinkedList<>();
stack.push(new Node(root, false));
while (!stack.isEmpty()) {
Node node = stack.pop();
if (!node.flag) {
if (node.treeNode.right != null) stack.push(new Node(node.treeNode.right, false));
stack.push(new Node(node.treeNode, true));
if (node.treeNode.left != null) stack.push(new Node(node.treeNode.left, false));
} else {
res.add(node.treeNode.val);
}
}
return res;
}
}
本文来自博客园,作者:klaus08,转载请注明原文链接:https://www.cnblogs.com/klaus08/p/15488526.html