二叉树递归问题

题目来源:

点击打开链接

题目描述:

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.

Example:

Input: 
         1
       /   \
      2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

  1. The sum of node values in any subtree won't exceed the range of 32-bit integer.
  2. All the tilt values won't exceed the range of 32-bit integer.

我的解决方案:

class Solution {
public:
    int findvalsum(TreeNode* root)
    {
        if(root==NULL)
          return 0;
        else 
          return root->val+findvalsum(root->left)+findvalsum(root->right);
    }
    
    int findTilt(TreeNode* root) {
        if(root==NULL)
          return 0;
        else
            return abs(findvalsum(root->left)-findvalsum(root->right))+findTilt(root->left)+findTilt(root->right);
          
    }
};

思考:
二叉树问题很容易想到用递归解决,本题比较有意思的一点是每个节点的tilt本身的计算需要用到左右子树的节点和.本身求节点和就可以用递归方便简单的解决,所以很容易想到我这种双重递归的办法完成求解,优点是简单好想,缺点也很明显,leetcode后台给出的运行时间是32ms,在所有解决方案里面效率倒数.成也递归,败也递归,双重递归的花销太大,那么有没有办法只用一重递归来解决这个问题呢?当然可以,每个节点的tile需要用到它的左右子树的节点值之和,这个本身需要通过递归求解,但是对于这个递归,每一层其实都已经知道了左右子树的节点和,那么也就能在每一层求到tilt值,如果把总的结果用一个全局的变量来存,那么在每一层递归总加值便可以求得,代码如下:


原作者alexander :

class Solution {
public:
    int findTilt(TreeNode* root) {
        int tilt = 0;
        sum(root, tilt);
        return tilt;
    }
private:
    int sum(TreeNode* node, int& tilt) {
        if (!node) {
            return 0;
        }
        int left = sum(node->left, tilt);
        int right = sum(node->right, tilt);
        tilt += abs(left - right);
        return node->val + left + right;
    }
};

同样在leetcode上面运行了一遍,运行时间位16ms,效率提高了一倍,做完题目之后还是要多思考多优化才行啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值