# 2641. Cousins in Binary Tree II ###### tags: `Leetcode` `Medium` `BFS` `Tree` Link: https://leetcode.com/problems/cousins-in-binary-tree-ii/description/ ## 思路 层序遍历 先算出当前一行所有children node的val sum 然后对当前一行的node的所有children node赋值 当前node的children的新val就是sum-当前node的children的val和 ## Code ```java= class Solution { public TreeNode replaceValueInTree(TreeNode root) { Queue<TreeNode> q = new LinkedList<>(); root.val = 0; q.add(root); while(!q.isEmpty()){ int size = q.size(); int sum = 0; List<TreeNode> temp = new ArrayList<>(); for(int i=0; i<size; i++){ TreeNode curr = q.poll(); temp.add(curr); if(curr.left!=null){ sum += curr.left.val; q.add(curr.left); } if(curr.right!=null){ sum += curr.right.val; q.add(curr.right); } } for(TreeNode curr:temp){ int t = sum; if(curr.left!=null) t -= curr.left.val; if(curr.right!=null) t -= curr.right.val; if(curr.left!=null) curr.left.val = t; if(curr.right!=null) curr.right.val = t; } } return root; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up