二叉树递归问题

来源:互联网 发布:java的三层架构是什么 编辑:程序博客网 时间:2024/05/20 01:45

题目来源:

点击打开链接

题目描述:

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     3Output: 1Explanation: Tilt of node 2 : 0Tilt of node 3 : 0Tilt of node 1 : |2-3| = 1Tilt 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,效率提高了一倍,做完题目之后还是要多思考多优化才行啊

0 0
原创粉丝点击