分层遍历
将每一层的节点遍历出来,利用LinkedList
,先压入根节点,循环遍历,循环的同时再将左节点,右节点分别加到尾部.
// 分层遍历 (TreeNode root)
if (root == null) return;
LinkedList<TreeNode> nodes = new LinkedList<>();
TreeNode last = root;
TreeNode nLast = root;
nodes.push(root);
while(!nodeStack.isEmpty()) {
TreeNode node = nodes.pop();
System.out.print(node.data + " ");
if (node.left != null) {
nodes.add(node.left);
nLast = node.left;
}
if (node.right != null) {
nodes.add(node.right);
nLast = node.right;
}
if (node == last) {
System.out.println(" ");
last = nLast;
}
}
前序遍历
前序遍历的顺序为:根–左--右,利用Stack
的先进后出原则.先将根节点推入栈,再将右节点和左节点依次推入,每次循环出栈.
// 前序遍历(TreeNode root)
if (root == null) return;
Stack<TreeNode> stacks = new Stack<>();
stacks.push(root);
while(!stacks.isEmpty()) {
TreeNode node = stacks.pop();
System.out.print(node.data + " ");
if (node.right != null) {
stacks.push(node.right);
}
if (node.left != null) {
stacks.push(node.left);
}
}
中序遍历
中序遍历的遍历顺序为:左–根--右,利用Stack
的先进后出原则.先将根节点推入栈,再将左节点推入,每次循环出栈时, 推入右节点.
// 中序遍历(TreeNode root)
if (root == null) return;
Stack<TreeNode> stacks = new Stack<>();
TreeNode cur = root;
while(!stacks.isEmpty() || cur != null) {
if (cur != null) {
stacks.push(cur);
cur = cur.left;
} else {
cur = stacks.pop();
System.out.print(node.data + " ");
cur = cur.right;
}
}
后序遍历
中序遍历的遍历顺序为:右–左--根,利用Stack
的先进后出原则.这里使用两个Stack
.先将根节点推入栈,再将右节点和左节点依次推入,循环第一个栈时将栈内的节点依次推入第二个栈中,最后遍历第二个栈.
// 后序遍历(TreeNode root)
if (root == null) return;
Stack<TreeNode> stacks = new Stack<>();
Stack<TreeNode> outs = new Stack<>();
stacks.push(root);
while(!stacks.isEmpty()) {
TreeNode node = stacks.pop();
outs.push(node);
if (node.left != null) {
stacks.push(node.left)
}
if (node.right != null) {
stacks.push(node.right)
}
}
while(!outs.isEmpty()) {
System.out.print(node.pop().data + " ");
}