学习笔记之二叉树的遍历

空扰寡人 提交于 2019-11-30 05:47:19

分层遍历

将每一层的节点遍历出来,利用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 + " ");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!