/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { /// <summary> /// 遍历二叉树,存储节点列表 /// </summary> Stack<TreeNode> S = new Stack<TreeNode>(); /// <summary> /// 先序遍历二叉树 /// </summary> /// <param name="node"></param> private void postNode(TreeNode node) { if (node != null) { S.Push(node); if (node.left != null) { postNode(node.left); } if (node.right != null) { postNode(node.right); } } } /// <summary> /// 以node为根节点的树的val之和 /// </summary> /// <param name="node"></param> /// <returns></returns> private int SumNode(TreeNode node) { int sum = 0; if (node != null) { sum += node.val; if (node.left != null) { sum += SumNode(node.left); } if (node.right != null) { sum += SumNode(node.right); } } return sum; } /// <summary> /// 获取每个节点的tilt值 /// </summary> /// <param name="node"></param> /// <returns></returns> private int GetTilt(TreeNode node) { if (node == null) { return 0; } else if (node.left == null && node.right == null) { return 0; } else { //计算左子树sum需要遍历左子树,然后累加每个节点的值 var left = 0; if (node.left != null) { left = SumNode(node.left); } //计算右子树sum需要遍历右子树,然后累加每个节点的值 var right = 0; if (node.right != null) { right = SumNode(node.right); } //根节点的tilt等于左右子树sum之差,//因此需要计算左子树sum和右子树sum var tilt = Math.Abs(left - right); return tilt; } } public int FindTilt(TreeNode root) { if (root != null) { //先遍历每个节点 postNode(root); //获得节点列表 var list = S.ToList(); //计算每个节点的tilt,再加到一起 var sum = 0; foreach (var l in list) { sum += GetTilt(l); } return sum; } else { return 0; } } }
https://leetcode.com/problems/binary-tree-tilt/#/description