力扣1022. 从根到叶的二进制数之和(二叉树的遍历思想解决)

时间:2025-02-10 07:25:51
/** * 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) { traverse(root); return res; } int path = 0; int res = 0; private void traverse(TreeNode root) { if (root == null) { return; } // Leaf root if (root.left == null && root.right == null) { // Add the value on the path to the res res += path << 1 | root.val; return; } // Change the value of path path = path << 1 | root.val; traverse(root.left); traverse(root.right); path = path >> 1; } }