对于广度优先遍历,需要有一个队列。
算法思路:
Java代码实现
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> BFS(TreeNode root) {
ArrayList<Integer> lists = new ArrayList<Integer>();
if(root==null)
return lists;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode tree = queue.poll();
if(tree.left!=null)
queue.offer(tree.left);
if(tree.right!=null)
queue.offer(tree.right);
lists.add(tree.val);
}
return lists;
}
}
深度优先遍历需要一个栈作为辅助
算法思路:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> BFS(TreeNode root) {
ArrayList<Integer> lists = new ArrayList<Integer>();
if(root==null)
return lists;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root)
while(!stack.isEmpty()){
TreeNode node = stack.pop()
lists.add(node.val)
if(node.rigth!=null){
stack.push(node.right)
}
if(node.left!=null){
stack.push(node.left)
}
}
return lists;
}
}
递归实现
public class Solution{
ArrayList<Integer> lists = new ArrayList<Integer>();
public ArrayList<Integer> BFS(TreeNode root) {
if(root==null)
return lists;
depthTraversal(root)
}
public void depthTraversal(TreeNode node){
self.lists.add(node.val)
if(node.left!=null){
depthTraversal(node.left)
}
if(node.right!=null){
depthTraversal(node.right)
}
}
}
原文:https://www.cnblogs.com/njuclc/p/13149499.html