这一题相对来说比较简单
给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。
示例 1
输入:
5
/
2 -3
返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。
示例 2
输入:
5
/
2 -5
返回 [2],只有 2 出现两次,-5 只出现 1 次。
提示: 假设任意子树元素和均可以用 32 位有符号整数表示。
我是这么想的:
1.后序遍历更改每个节点的值为子树元素和(虽然实际项目中对传入参数直接修改并不太好)
2.统计出现最多的元素。
public int[] findFrequentTreeSum(TreeNode root) {
int max=0;
Post(root);
Map<Integer,Integer> m=new HashMap<Integer,Integer>();//<num,count>
Stack<TreeNode> s=new Stack<TreeNode>();
List<Integer> list=new ArrayList<Integer>();
do {
while(root!=null) {
s.push(root);
root=root.left;
}
if(!s.empty()) {
root=s.pop();
if(!m.containsKey(root.val))
m.put(root.val, 1);
else
m.put(root.val, m.get(root.val)+1);
root=root.right;
}
}while(root!=null||!s.empty());
for(int count:m.values())
max=Math.max(count, max);
for(int num:m.keySet())
if(m.get(num)==max)
list.add(num);
int len=list.size(),ans[]=new int[len];
for(int i=0;i<len;i++)
ans[i]=list.get(i);
return ans;
}
void Post(TreeNode root) {
if(root==null)
return;
Post(root.left);
Post(root.right);
if(root.left!=null)
root.val+=root.left.val;
if(root.right!=null)
root.val+=root.right.val;
}