十五:二叉樹根節點到葉節點權值最大和

題目

二叉樹每個結點都有一個int型權值, 給定一棵二叉樹, 要求計算出從根結點到
葉結點的所有路徑中, 權值和最大的值爲多少。

實現

package com.jpg.coding;

public class MaxSum {

	public static class Node {
		public int value;
		public Node left;
		public Node right;
		
		public Node(int value) {
			this.value = value;
		}
	}
	
	//只有在到達葉節點的時候,有可能更新
	public static int maxSum = Integer.MIN_VALUE;
	
	public static int maxPath(Node head) {
		p(head, 0);
		return maxSum;
	}
	
	//從根節點出發到當前節點上方的節點,獲得的路徑和
	public static void p(Node x, int pre) {
		if (x.left == null && x.right == null) {
			maxSum = Math.max(maxSum, pre + x.value);
		}
		if (x.left != null) {
			p(x.left, pre + x.value); //表示從根節點出發到x節點獲得的路徑和
		}
		if (x.right != null) {
			p(x.right, pre + x.value);
		}
	}
	
	//dp套路
	public static int maxDis(Node head) {
		if (head == null) {
			return 0;
		}
		return process(head);
	}
	
	//表示以x爲頭的整棵樹上,最大路徑和是多少,必須從x出發,到葉子節點
	public static int process(Node x) {
		if (x.left == null && x.right == null) {
			return x.value;
		}
		if (x.left != null && x.right != null) {
			return x.value + Math.max(process(x.left), process(x.right));
		}
		return (x.left != null ? process(x.left) : process(x.right)) + x.value;
	}
	
	public static void main(String[] args) {
		Node head = new Node(4);
		head.left = new Node(1);
		head.left.right = new Node(5);
		head.right = new Node(-7);
		head.right.left = new Node(3);
		System.out.println(maxPath(head));
		System.out.println(maxDis(head));
	}
	
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章