zoukankan      html  css  js  c++  java
  • 二叉树的深度

    输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

    思考递归(例如对于关于树的相关操作):要从树叶到树根思考代码的运行过程!

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    
        TreeNode(int x) {
            val = x;
        }
    }
    
    
    class Solution {
       public static void main(String[] args) {
            TreeNode node = new TreeNode(3);
            node.left = new TreeNode(9);
            node.right = new TreeNode(20);
            node.right.left = new TreeNode(15);
            node.right.right = new TreeNode(7);
            Solution solution = new Solution();
            int depth = solution.maxDepth(node);
            System.out.println("depth: " + depth);
        }
    
    
        public int maxDepth(TreeNode node) {
            if (node == null) return 0;
            return Math.max(maxDepth(node.left), maxDepth(node.right)) + 1;
        }
    
    
    }

    题目来源:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof

  • 相关阅读:
    程序中图片透明 函数(使用SetBkColor API函数)
    编程中使用锁
    event内存泄漏
    diskcache
    linux内核管理
    Vue
    Paxos算法
    索引以及页和区
    CoreRT
    二叉树
  • 原文地址:https://www.cnblogs.com/iuyy/p/13710370.html
Copyright © 2011-2022 走看看