0
点赞
收藏
分享

微信扫一扫

二叉树的遍历与搜索


记得深度优先用的是栈,广度优先用的是队列

深度优先包括我们之前说的前序中序后续遍历方法

广度优先就是层次遍历


package toyprogram;

import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.ArrayBlockingQueue;

class TreeNode {
Object val = null;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
public TreeNode(TreeNode l,TreeNode r,Object o) {
left=l;
right=r;
val=o;
}

}

public class Solution {
public static void main(String[] args) {
TreeNode treeNode=getTree();
depthFirstSearch(treeNode);
System.out.println("*****");
breadthFirstSearch(treeNode);
}
public static TreeNode getTree(){
TreeNode G = new TreeNode(null, null, 'G');
TreeNode H = new TreeNode(null, null, 'H');
TreeNode F = new TreeNode(G, H, 'F');
TreeNode D = new TreeNode(null, F, 'D');
TreeNode E = new TreeNode(null, null, 'E');
TreeNode B = new TreeNode(D, E, 'B');
TreeNode C = new TreeNode(null, null, 'C');
TreeNode A = new TreeNode(B, C, 'A');
return A;
}

public static void breadthFirstSearch(TreeNode root){
Queue<TreeNode> queue=new ArrayBlockingQueue<TreeNode>(10);

if (root!=null) {
queue.add(root);
}else {
return;
}

while (!queue.isEmpty()) {
TreeNode t=queue.poll();
System.out.print(t.val);
if (t.left!=null)
queue.add(t.left);

if(t.right!=null)
queue.add(t.right);

}
}

public static void depthFirstSearch(TreeNode root) {
Stack<TreeNode> s=new Stack<>();
if (root!=null) {
s.push(root);
}else {
return;
}

while (!s.empty()) {
TreeNode treeNode=s.pop();
System.out.print(treeNode.val);
if (treeNode.right!=null)
s.push(treeNode.right);

if (treeNode.left!=null)
s.push(treeNode.left);


}
}
}

这两天面试,人家让写二叉树的查找,想了一下,代码如下:

/**
* 递归解法
*
* @param t
* @param target
* @return
*/
public static TreeNode findTreeWithRecursion(TreeNode t, int target) {

if (t != null) {
if (t.val == target) {
return t;
}
TreeNode t1, t2;
t1 = findTreeWithRecursion(t.left, target);
if (t1 != null)
return t1;

// 如果把下面的代码 上移3行 效率就会降低很多
// 大家能理解么?
t2 = findTreeWithRecursion(t.right, target);
if (t2 != null)
return t2;

return null;

} else {
return null;
}

}

/**
* 非递归解法
*
* @param t
* @param target
* @return
*/
public static TreeNode findTreeWithoutRecursion(TreeNode t, int target) {

Stack<TreeNode> s = new Stack<>();
if (t != null) {
s.push(t);
} else {
return null;
}

while (!s.empty()) {
TreeNode treeNode = s.pop();
if (t.val == target) {
return t;
}
if (treeNode.right != null) {
s.push(treeNode.right);
}
if (treeNode.left != null) {
s.push(treeNode.left);
}

}

return null;
}



举报

相关推荐

0 条评论