学习笔记之二叉树的遍历

分层遍历

将每一层的节点遍历出来,利用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 + " ");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值