[LeetCode OJ]Maximum Depth Of Binary Tree

来源:互联网 发布:域名ip查询 编辑:程序博客网 时间:2024/06/04 19:56

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

貌似就是个二叉树深度,早就忘得透透的了,又回去看了看,这个递归想了好久好久唉。。。

Java版本

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {        if(root == null) {            return 0;        }                int left = maxDepth(root.left);        int right = maxDepth(root.right);        return left > right ? left + 1 : right + 1;    }}
最后这个还可以调用java max

return max(left, right) + 1;


C++版本

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxDepth(TreeNode *root) {        if(root == NULL)            return 0;                int left = maxDepth(root->left);        int right = maxDepth(root->right);                return left > right ? left + 1 : right + 1;    }};


0 0
原创粉丝点击