二叉树深度遍历和广度遍历

https://blog.csdn.net/weixin_39912556/article/details/82852749

 

package Method;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
import java.util.Stack;

/**
 * Created by joyce on 2019/9/11.
 */
public class TreeMain {
    private static class TreeNode {
        public TreeNode left;
        public TreeNode right;
        private String val;
        public TreeNode(String _val) {
            val = _val;
        }
        public void echo() {
            System.out.println(val);
        }

        public TreeNode setLeft(TreeNode left) {
            this.left = left;
            return this;
        }

        public TreeNode setRight(TreeNode right) {
            this.right = right;
            return this;
        }
    }

    public static void main(String [] f) {
        TreeNode D = new TreeNode("D");
        TreeNode E = new TreeNode("E");
        TreeNode F = new TreeNode("F");
        TreeNode G = new TreeNode("G");
        TreeNode B = new TreeNode("B").setLeft(D).setRight(E);
        TreeNode C = new TreeNode("C").setLeft(F).setRight(G);
        TreeNode A = new TreeNode("A").setLeft(B).setRight(C);
        DB(A);
        DBD(A);
        WB(A);

    }

    /**
     * 深度
     * @param root
     */
    public static void DB(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode treeNode = stack.pop();
            treeNode.echo();
            if(treeNode.right != null) {
                stack.push(treeNode.right);
            }
            if(treeNode.left != null) {
                stack.push(treeNode.left);
            }
        }
    }

    /**
     * 深度 递归
     * @param root
     */
    public static void DBD(TreeNode root) {
        if(root == null)
            return;
        root.echo();
        DBD(root.left);
        DBD(root.right);
    }

    /**
     * 广度
     * @param root
     */
    public static void WB(TreeNode root) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            TreeNode treeNode = deque.remove();
            treeNode.echo();
            if(treeNode.left != null) {
                deque.add(treeNode.left);
            }
            if(treeNode.right != null) {
                deque.add(treeNode.right);
            }
        }
    }
}

 

posted on 2019-09-11 12:06  silyvin  阅读(701)  评论(0编辑  收藏  举报