Leetcode563. 二叉树的坡度

Leetcode563. 二叉树的坡度

题目:
给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。

示例:

输入:
         1
       /   \
      2     3
输出:1
解释:
结点 2 的坡度: 0
结点 3 的坡度: 0
结点 1 的坡度: |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1

题解:

  1. 先定义一个变量sum=0;
  2. 对二叉树进行顺序遍历,然后求左节点和右节点差的绝对值,再累加到sum上,直到左右节点都为空停止。
    java代码:
  /**迭代
     * @param root
     * @return
     */
    public static int findTilt(TreeNode root) {
        int sum = 0;
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            int s1 = 0, s2 = 0;
            if (node.left != null) {
                s1 = node.left.value;
                queue.add(node.left);
            }
            if (node.right != null) {
                s2 = node.right.value;
                queue.add(node.right);
            }
            int tmp = Math.abs(s1 - s2);
            sum += tmp;
        }
        return sum;
    }



    static int tilt;

    /**
     * 递归
     * @param root
     * @return
     */
    public static int findTilt2(TreeNode root) {
        if (root == null) return 0;
        int leftSum = findTilt2(root.left);
        int rightSum = findTilt2(root.right);
        tilt += Math.abs(leftSum - rightSum);
        return leftSum + rightSum + root.value;
    }

你可能感兴趣的:(Leetcode,leetcode)