位运算符和移位运算符
<< 左移 乘2
>> 右移 除2
| 按位 or
& 按位 and
^ 按位 异或 不同为1 ,相同为0
应用示例二进制转10进制
https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int SumRootToLeaf(TreeNode root)
{
return DFS(root, 0);
}
public int DFS(TreeNode root, int val)
{
if (root == null)
{
return 0;
}
val = (val << 1) | root.val;
if (root.left == null && root.right == null)
{
return val;
}
return DFS(root.left, val) + DFS(root.right, val);
}
}