二叉树

作者: YocnZhao | 来源:发表于2019-06-17 21:27 被阅读0次
    • 深度优先遍历 递归 DFS
     public void visitNode(TreeNode node, Bean bean) {
            if (node == null) {
                return;
            }
            bean.num++;
            visitNode(node.left, bean);
            visitNode(node.right, bean);
        }
    
    • 广度优先遍历 递归BFS
    private void visitBFS(Queue<TreeNode> src) {
            if (src.isEmpty()) {
                return;
            }
            Queue<TreeNode> tar = new ArrayDeque<>();
            while (!src.isEmpty()) {
                TreeNode node = src.poll();
                LogUtil.Companion.d(node.val);
                if (node.left != null) {
                    tar.add(node.left);
                }
                if (node.right != null) {
                    tar.add(node.right);
                }
            }
            visitBFS(tar);
        }
    
    • 二叉树的最大最小深度
    public class DepthOfBinaryTree {
    
        public void test() {
            int min = minDepth(BinaryTreeUtil.prepareANode2());
            int max = maxDepth(BinaryTreeUtil.prepareANode2());
            LogUtil.Companion.d("min->" + min);
            LogUtil.Companion.d("max->" + max);
        }
    
        int max;
    
        public int maxDepth(TreeNode root) {
            visitMaxNode(root, 1);
            return max;
        }
    
        private void visitMaxNode(TreeNode node, int deep) {
            if (node == null) {
                return;
            }
            if (node.left == null && node.right == null) {
                //说明是叶子节点
                if (deep > max) {
                    max = deep;
                }
            }
            visitMaxNode(node.left, deep + 1);
            visitMaxNode(node.right, deep + 1);
        }
    
        int min = 0;
    
        public int minDepth(TreeNode root) {
            visitMinNode(root, 1);
            return min;
        }
    
        private void visitMinNode(TreeNode node, int deep) {
            if (node == null) {
                return;
            }
            if (node.left == null && node.right == null) {
                //说明是叶子节点
                if (min == 0) {
                    min = deep;
                }
                if (deep < min) {
                    min = deep;
                }
            }
            visitMinNode(node.left, deep + 1);
            visitMinNode(node.right, deep + 1);
        }
    }
    
    • 判断二叉树是否中轴对称
    public boolean isSymmetric(TreeNode root) {
            if (root == null) return true;
            return dfs(root.left, root.right);
        }
    
        public boolean dfs(TreeNode left, TreeNode right) {
            if (left == null || right == null) return left == right;
            if (left.val != right.val) return false;
            return dfs(left.left, right.right) && dfs(left.right, right.left);
        }
    

    相关文章

      网友评论

          本文标题:二叉树

          本文链接:https://www.haomeiwen.com/subject/drftqctx.html