Maximum Depth of Binary Tree_DFS

DFS, Stack

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

์ž๋ฃŒ๊ตฌ์กฐ : Stack

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ํŠธ๋ฆฌ ๋…ธ๋“œ๋ฅผ ๋ฃจํŠธ์—์„œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ์Šคํƒ์— ๋„ฃ๋Š”๋‹ค. (๋…ธ๋“œ๋ฅผ ๋„ฃ๋Š” ์Šคํƒ์™€ ๊นŠ์ด ๊ฐ’ ๋„ฃ๋Š” ์Šคํƒ, ๊นŠ์ด ๊ฐ’์€ root=1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.) 2. pop()ํ•˜๋ฉด์„œ ์™ผ์ชฝ ์ž์‹๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹์ด ์žˆ์œผ๋ฉด pushํ•œ๋‹ค. 3. ๋…ธ๋“œ ์Šคํƒ์— ๋…ธ๋“œ๋ฅผ ๋„ฃ์„ ๋•Œ๋งˆ๋‹ค ๊นŠ์ด๊ฐ’์€ +1์”ฉ ์ฆ๊ฐ€ํ•œ๋‹ค. 4. ๊นŠ์ด ๊ฐ’์€ 1->2->3->4.. ์ฆ๊ฐ€ํ•˜๋ฏ€๋กœ Math.max(value, max) ๋กœ ๊นŠ์ด ๊ฐ’์„ ๋น„๊ตํ•˜๋ฉฐ ์ตœ๋Œ“๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {//DFS, Stack
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> Vstack = new Stack<>();
        
        stack.push(root);
        Vstack.push(1);//root has 1 depth itself.
        int max = 0;
        while(!stack.isEmpty()) {//till stack is empty, push and pop node and depth value to stack.
            TreeNode node = stack.pop();
            int value = Vstack.pop();
            max = Math.max(max,value);
            if(node.left != null) {
                stack.push(node.left);
                Vstack.push(value+1);
            }
            if(node.right != null) {
                stack.push(node.right);
                Vstack.push(value+1);
            }
        }
        return max;
    }
}

Last updated

Was this helpful?