新手算法学习之路----二叉树(深度和广度优先算法)

深度优先算法(DFS):和先序遍历差不多,是沿着树的深度遍历树的节点,尽可能深的搜索树的分支,一般是跟节点,左分支和右分支的顺序来进行查找的。因此可以借助堆栈的数据结构,由于堆栈是后进先出的顺序,由此可以先将右子树压栈,然后再对左子树压栈,这样一来,左子树结点就存在了栈顶上,因此某结点的左子树能在它的右子树遍历之前被遍历。

代码:

public void DepthFirst(TreeNode root) {
        // write your code here
        if(root == null) return 0;
        ArrayList<Integer> a = new ArrayList<Integer>();
        Stack<TreeNode> s = new Stack<TreeNode>();
        s.push(root);
        while(!s.empty()){
            root = s.peek();
            a.add(root.val);
            s.pop();
            if(root.left){ 
                s.push(root.left);
            }
            if(root.right){
                s.push(root.right);
            }
        }
    }

 广度优先算法(BFS):是从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则算法中止。如二叉树,A 是跟节点是第一个访问的,然后顺序是 B、C(BC在一层里面),然后再是 D、E、F、G(在一层里面)。利用到队列就可以实现,将上述代码改一下就可以了

Java代码:

 public void WidthFirst(TreeNode root) {
        // write your code here
        if(root == null) return 0;
        ArrayList<Integer> a = new ArrayList<Integer>();
        Queue<TreeNode> s = new Queue<TreeNode>();
        s.push(root);
        while(!s.empty()){
            root = s.peek();
            a.add(root.val);
            s.remove();    //移除队列的头部元素相当于s.pop();
            if(root.left){ 
                s.push(root.left);
            }
            if(root.right){
                s.push(root.right);
            }
        }
    }

 

posted @ 2017-07-12 15:19  JunLiu37  阅读(348)  评论(0编辑  收藏  举报