zoukankan      html  css  js  c++  java
  • 104. Maximum Depth of Binary Tree

    原题链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
    这道题目级别为“Easy”,也确实是简单!
    不废话,直接使用递归实现深度优先搜索即可:

    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        static class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
    
            public TreeNode(int val) {
                this.val = val;
            }
        }
    
        public static void main(String[] args) {
            TreeNode root = new TreeNode(1);
    
            TreeNode rootLeft = new TreeNode(2);
            TreeNode rootRight = new TreeNode(3);
            root.left = rootLeft;
            root.right = rootRight;
    
            TreeNode leftLeft = new TreeNode(3);
            TreeNode leftRight = null;
            rootLeft.left = leftLeft;
            rootLeft.right = leftRight;
    
            TreeNode rightLeft = new TreeNode(2);
            TreeNode rightRight = null;
            rootRight.left = rightLeft;
            rootRight.right = rightRight;
    
            Solution s = new Solution();
            System.out.println(s.maxDepth(root));
        }
    
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return dfs(root, 1);
        }
    
        public int dfs(TreeNode node, int currentDepth) {
    
            int leftDepth = currentDepth, rightDepth = currentDepth;
            if (node.left != null) {
                leftDepth = dfs(node.left, currentDepth + 1);
            }
            if (node.right != null) {
                rightDepth = dfs(node.right, currentDepth + 1);
            }
    
            return leftDepth > rightDepth ?
                    (leftDepth > currentDepth ? leftDepth : currentDepth) :
                    (rightDepth > currentDepth ? rightDepth : currentDepth);
        }
    }
    
  • 相关阅读:
    洛谷P4547 [THUWC2017]随机二分图
    洛谷P4590 [TJOI2018]游园会
    洛谷P4099 [HEOI2013]SAO
    #4719. 内凸包
    #1612. 天平(scales)
    #3164. 「CEOI2019」立方填词
    #4728. 问题求解
    #2754. Count(count)
    sa模板
    bzoj 2553: [BeiJing2011]禁忌
  • 原文地址:https://www.cnblogs.com/optor/p/8538637.html
Copyright © 2011-2022 走看看