二叉樹的深度

簡單的遞歸

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int maxn=0;
    public int TreeDepth(TreeNode root) {
        if(root==null)
            return 0;
        dfs(root,0);
        return maxn;
        
    }
    void dfs(TreeNode tree,int ans){
        if(tree==null){
            if(ans>maxn)
                maxn=ans;
            return;
        }
        dfs(tree.left,ans+1);
        dfs(tree.right,ans+1);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章