将任意一颗二叉树转变为每一个节点都是另外两个孩子节点的和
2014-06-30 16:21
381 查看
50 / \ / \ 8 2 / \ /\ / \ / \ 3 5 1 30
package tree; public class ConvertSumP { /** * 将任意一颗二叉树转变为每一个节点都是另外两个孩子节点的和,要求 * 只能增加某一个节点的值,节点为null视为0 * @param args */ public static void convert(TreeNode root){ if(root==null||(root.left==null&&root.right==null)) return; convert(root.left); convert(root.right); int left = getsum(root.left); int right = getsum(root.right); if(root.value==left+right){ return; }else if(root.value<left+right){ root.value = left+right; }else{ if(root.left!=null){ root.left.value+=root.value-left-right; convert(root.left); }else{ root.right.value += root.value-left-right; convert(root.right); } } } private static int getsum(TreeNode root) { if(root==null) return 0; return root.value; } public static void print(TreeNode root){ if(root==null) return; System.out.print(root.value+" "); print(root.left); print(root.right); } public static void main(String[] args) { TreeNode root = new TreeNode(50); root.left = new TreeNode(7); root.right = new TreeNode(2); root.left.left = new TreeNode(3); root.left.right = new TreeNode(5); //root.right.left = new TreeNode(1); root.right.right = new TreeNode(30); print(root); convert(root); System.out.println(); print(root); } }
50 / \ / \ 19 31 / \ / \ / \ / \14 5 1 30
相关文章推荐
- 查看一颗二叉树的每个节点的值是否都是其左右两个孩子节点值的和
- 求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数,比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,
- 给定一颗二叉树,以及其中的两个node(地址均非空),要求给出这两个node的一个公共父节点,使得这个父节点与两个节点的路径之和最小。
- 查找二叉树任意两个节点的父节点
- 求一个二叉树中任意两个节点间的最大距离
- 【每日面试题】求一个二叉树中任意两个节点间的最大距离
- Cracking-- 4.7 在一颗二叉树中找两个节点的第一个共同祖先
- 求一颗二叉树中最远的两个节点的距离
- 求二叉树的任意两个节点的最近公共祖先
- 二叉树系列——二叉树中任意两个节点之间的最短路径
- 二叉树中任意两个节点之间的最大距离
- 二叉树,给定任意两个节点,寻找最近的父节点
- 每天学习一算法系列(34)(求一个二叉树中任意两个节点间的最大距离,两个节点的距离的定义是这两个节点间边的个数)
- 【二叉树9】二叉树中任意两个节点的最大路径和
- 若用链表存储一棵二叉树时,每个节点除数据域外,还有指向左孩子和右孩子的两个指针,在这种存储结构中,n歌节点的二叉树共有2N个指针域,其中有N-1个指针域存放了地址,有N+1个指针是空指针。
- 找出二叉树中任意两个节点的最低公共父节点
- 求一个二叉树中任意两个节点间的最大距离
- 二叉树中任意两个节点间的距离 源码
- 求二叉树的任意两个节点A,B的最邻近的公共父节点
- 求解一颗二叉树中两个叶子节点最长的路径