자바 이 진 트 리 깊이 구현

이 진 트 리 의 깊이 를 구 하려 면 이 진 트 리 를 입력 하 십시오.뿌리 결점 에서 잎 결점 까지 순서대로 지나 가 는 결점 (뿌리, 잎 결점 포함) 은 나무의 한 경 로 를 형성 하고 가장 긴 경로 의 길 이 는 나무의 깊이 이다.
코드
해법
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

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

    /**
     *      
     * @param root
     * @return
     */
    public static int treeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //         
        int left = treeDepth(root.left);
        //         
        int right = treeDepth(root.right);
        //  root   =          + 1
        return left >= right ? (left + 1) : (right + 1);
    }

해법
public int treeDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        Stack stack = new Stack<>();
        stack.push(root);
        while (!root.isEmpty()) {
            depth++;
            int size = stack.size();
            while (size > 0) {
                TreeNode current = stack.pop();
                if (current.right != null) {
                    stack.push(current.right);
                }
                if (current.left != null) {
                    stack.push(current.left);
                }
                size--;
            }
        }
        return depth;
    }

좋은 웹페이지 즐겨찾기