满二叉树转为求和树(中序后序,构造二叉树齐力解决,太经典了)
主要通过后序遍历求和,加一个sum属性,表示子树的和
import java.util.*; public class Main { static class TreeNode{ int data; int sum; public TreeNode left; public TreeNode right; TreeNode(int data){ this.data = data; } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String a=sc.nextLine(); String[] preStr=a.split(" "); int[] pre=new int[preStr.length]; for(int i=0;i<preStr.length;i++) { pre[i]=Integer.valueOf(preStr[i]); } String b=sc.nextLine(); String[] inStr=b.split(" "); int[] in=new int[inStr.length]; for(int i=0;i<in.length;i++) { in[i]=Integer.valueOf(inStr[i]); } TreeNode head=reConstructBinaryTree(pre, in); postOrder(head); inOrder(head); } public static TreeNode reConstructBinaryTree(int[] pre,int[] in) { if(pre.length==0||in.length==0) return null; TreeNode head=new TreeNode(pre[0]); int mid=0; for(int i=0;i<in.length;i++) { if(pre[0]==in[i]) { mid=i; break; } } int[] inleft=Arrays.copyOfRange(in, 0, mid); int[] preleft=Arrays.copyOfRange(pre, 1, mid+1); int[] inright=Arrays.copyOfRange(in, mid+1, in.length); int[] preright=Arrays.copyOfRange(pre, mid+1, pre.length); head.left=reConstructBinaryTree(preleft, inleft); head.right=reConstructBinaryTree(preright, inright); return head; } public static void postOrder(TreeNode head) { int flag; //用来表示是否在处理栈顶标志,1就是处理栈顶 Stack<TreeNode> stack=new Stack<>(); TreeNode p; //用来判断是否前一个已经访问的节点 if(head!=null) { TreeNode temp=head; do { while(temp!=null) { stack.push(temp); temp=temp.left; } p=null; flag=1; while(!stack.isEmpty()&&flag==1) { temp=stack.peek(); if(temp.right==p) { int tleft=temp.left==null?0:(temp.left.data+temp.left.sum); int tright=temp.right==null?0:(temp.right.sum+temp.right.data);//就是子树在这个地方改一下 temp.sum=tleft+tright; stack.pop(); p=temp; } else { temp=temp.right; flag=0; } } } while(!stack.isEmpty()); } } public static void inOrder(TreeNode head) { Stack<TreeNode> stack=new Stack<>(); if(head!=null) { TreeNode temp=head; while(!stack.isEmpty()||temp!=null) { while(temp!=null) { stack.push(temp); temp=temp.left; } if(!stack.isEmpty()) { temp=stack.pop(); System.out.print(temp.sum+" "); temp=temp.right; } } } } }
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/11255261.html

浙公网安备 33010602011771号