算法刷题之二叉树的深度

采用递归的思想,依次比较每个节点的左子树和右子树的深度,然后返回左右子节点的最大深度(+1是算上顶点的值)。

package tree;

class TreeNode {
     int val = 0;
     TreeNode left = null;
     TreeNode right = null;
     public TreeNode(int val) {
        this.val = val;
     }
 }


public class TreeDeepth {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.right = new TreeNode(3);
        treeNode.left.left = new TreeNode(4);
        treeNode.left.right = new TreeNode(5);
        treeNode.left.left.left = new TreeNode(6);
        treeNode.left.left.left.left = new TreeNode(7);

        System.out.println(getTreeDeepth(treeNode));
    }

    private static int getTreeDeepth(TreeNode treeNode) {
        if(treeNode==null){
            return 0;
        }
        int left = getTreeDeepth(treeNode.left);
        int right = getTreeDeepth(treeNode.right);
        return Math.max(left,right)+1;
    }


}

 

你可能感兴趣的:(算法刷题)