1/10/2022

[LeetCode] 1022. Sum of Root To Leaf Binary Numbers

 Problem : https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/

Use DFS to get the result.

Time complexity = O(N)


/**
 * 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 {
    public int sumRootToLeaf(TreeNode root) {
        // dfs
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        
        stack1.push(root);
        stack2.push(0);
        
        int result = 0;
        
        while(!stack1.isEmpty()) {
            TreeNode node = stack1.pop();
            int tmp = stack2.pop();
            
            tmp = (tmp << 1) | node.val;
            if (node.left == null && node.right == null) {
                result += tmp;
            }
            
            if (node.right != null) {
                stack1.push(node.right);
                stack2.push(tmp);
            }
            
            if (node.left != null) {
                stack1.push(node.left);
                stack2.push(tmp);
            }
        }
        
        return result;
    }
}

No comments:

Post a Comment