数据结构面试中常见算法小结

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

一、二叉树遍历思想:

1、非递归前序遍历

List作栈,top为栈针

While循环

当前点非空,输出

右子非空,入栈

左子非空,入栈

栈非空,栈顶为当前点,出栈;否则break

2、非递归中序遍历

List作栈,top为栈针

While循环(但前点非空或栈非空)

当前点非空,入栈,左子为当前点;

否则,栈顶为当前点,出栈;输出,右子为当前点

3、非递归后序遍历

List1作数据栈,list2作标识栈,top为数据栈针,tag为标识作判断用

Do循环

While循环(当前点非空)

入数据栈,标识栈对应设1;左子为当前点。(本内循环相当于把所有左子入栈)数据栈顶为当前点,标识栈顶为tag且出栈

Tag为1,数字2进标识栈,右子为当前点

否则为2,数据栈出栈顶,输出,当前点为null;

While(当前点非空或数据栈非空)---与do配套

二叉树的各遍历算法:

package com.job.basic;

import java.util.*;

public class BinaryTree {

//递归前序遍历

public void rPreOrder(Node root) {

if (root != null) System.out.print(root.data);

if (root.left != null) rPreOrder(root.left);

if (root.right != null) rPreOrder(root.right);

}

//前序遍历

public void preOrder(Node root) {

ArrayList stack = new ArrayList();// 使用ArrayList作为堆栈 int top = -1;// 栈指针

Node current = root;

while (true) {

if (current != null) System.out.print(current.data);

// 右子节点进栈

if (current.right != null) {

stack.add(current.right);

top++;

}

// 左子节点进栈

if (current.left != null) {

stack.add(current.left);

top++;

}

// 如果栈内还有节点,栈顶节点出栈

if (top > -1) {

current = stack.get(top);

stack.remove(top--);

} else {

break;

}

}

}

// 递归中序遍历

public void rInOrder(Node root) {

if (root != null) {

if (root.left != null) rInOrder(root.left);

System.out.print(root.data);

if (root.right != null) rInOrder(root.right);

}

}

// 中序遍历

public void inOrder(Node root) {

if (root != null) {

ArrayList stack = new ArrayList();

int top = -1;

Node current = root;

while (current != null || top > -1) {

// 一直寻找左孩子,将路上节点都进栈,如果左孩子为null,返回父节点,再从右孩子找 if (current != null) {

stack.add(current);

top++;

current = current.left;

} else {

current = stack.get(top);// 取出栈顶节点,并继续遍历右子树 stack.remove(top--);

System.out.print(current.data);

current = current.right;

}

}

}

}

// 递归后续遍历

public void rPostOrder(Node root) {

if (root != null) {

if (root.left != null) rPostOrder(root.left);

if (root.right != null) rPostOrder(root.right);

System.out.print(root.data);

}

}

//后序遍历:可以被遍历的节点都要进栈出栈两次,所以添加第二个栈用来标示进栈次数 public void postOrder(Node root) {

if (root != null) {

ArrayList stack1 = new ArrayList();

ArrayList stack2 = new ArrayList();

int top = -1;

int tag;

Node current = root;

do {

while (current != null) { //将所有左子节点进栈

stack1.add(current);

stack2.add(1);

top++;

current = current.left;

}

//取出栈顶节点,并判断其标志位

current = stack1.get(top);

tag = stack2.get(top);

stack2.remove(top);

if (tag == 1) {

// tag为1,表明该节点第一次进栈,还需要进栈一次,同时修改标志位

current = current.right;

stack2.add(2);

} else {

// tag不位0,表明非首次进栈,可以遍历了。

stack1.remove(top);

top--;

System.out.print(current.data);

current = null;

}

} while (current != null || top != -1);

}

}

}

class Node {

public int data;

相关文档
最新文档