zoukankan      html  css  js  c++  java
  • leetcode — maximum-depth-of-binary-tree

    /**
     *
     * Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
     *
     *
     *
     * Given a binary tree, find its maximum depth.
     *
     * The maximum depth is the number of nodes along the longest path from the root node
     * down to the farthest leaf node.
     */
    public class MaxDepthOfBinaryTree {
    
    
        /**
         * 求出二叉树树的深度,使用深度优先
         *
         * @param root
         * @return
         */
        public int maxDepth (TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftMax = 1;
            int rightMax = 1;
            leftMax += maxDepth(root.leftChild);
            rightMax += maxDepth(root.rightChild);
    
            return Math.max(leftMax, rightMax);
        }
    
    
        public TreeNode createTree (char[] treeArr) {
            TreeNode[] tree = new TreeNode[treeArr.length];
            for (int i = 0; i < treeArr.length; i++) {
                if (treeArr[i] == '#') {
                    tree[i] = null;
                    continue;
                }
                tree[i] = new TreeNode(treeArr[i]-'0');
            }
            int pos = 0;
            for (int i = 0; i < treeArr.length && pos < treeArr.length-1; i++) {
                if (tree[i] != null) {
                    tree[i].leftChild = tree[++pos];
                    if (pos < treeArr.length-1) {
                        tree[i].rightChild = tree[++pos];
                    }
                }
            }
            return tree[0];
        }
    
        private class TreeNode {
            TreeNode leftChild;
            TreeNode rightChild;
            int value;
    
            public TreeNode(int value) {
                this.value = value;
            }
    
            public TreeNode() {
    
            }
        }
    
        public static void main(String[] args) {
            MaxDepthOfBinaryTree depthOfBinaryTree = new MaxDepthOfBinaryTree();
            char[] arr = new char[]{'3','9','2','#','#','1','7'};
    
            System.out.println(depthOfBinaryTree.maxDepth(depthOfBinaryTree.createTree(arr)));
        }
    }
    
  • 相关阅读:
    中移动ipv6-老毛子固件获取ipv6设置
    win7-win10 禁用IPV6临时地址
    辅助调用函数【call,apply,bind】
    Unraid修改docker镜像地址&默认启动
    docker基本入门知识-小白向
    [不止于代码]Unraid基本使用速记
    Dockerfile文件说明
    Git之pull,fetch差别
    代码片段添加智能提示,打造一款人见人爱的ORM框架
    新定义三层,指挥官模式
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7807079.html
Copyright © 2011-2022 走看看