Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all nodes' tilt.
开始用的是一种很naive的想法,将tilt和sum分为两个过程,tilt过程是需要调用sum的,tilt过程通过递归向上传递tilt的值,因为要计算tilt就要计算sum,为了避免多次重复调用sum,用了一个map记录中间的结果。
结果跑出来的代码很慢,看了一下dicuss,发现可以使用一个全局的变量tilt来存储最后的结果,那么tilt在sum递归链的返回过程之中就可以算出来了。
之前比较naive的代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
HashMap<TreeNode,Integer> map = new HashMap<>();
public int findTilt(TreeNode root) {
return tilt(root);
}
private int sum (TreeNode root,HashMap<TreeNode,Integer> map)
{
if(map.containsKey(root))
return map.get(root);
if(root==null)
return 0;
int val=sum(root.left,map)+sum(root.right,map)+root.val;
map.put(root,val);
return val;
}
private int tilt (TreeNode root)
{
if(root==null)
return 0;
int val=Math.abs(sum(root.left,map)-sum(root.right,map));
return tilt(root.left)+tilt(root.right)+val;
}
}
修改后
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int tilt =0;
public int findTilt(TreeNode root) {
helper(root);
return tilt;
}
private int helper (TreeNode root)
{
if(root==null)
return 0 ;
int left = helper(root.left);
int right= helper(root.right);
tilt+=Math.abs(left-right);
return left+right+root.val;
}
}