根節點到葉子節點的和值(根節點逐步升位)
package leetcode;
/*Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.*/
public class Sum_root_to_leaf_numbers {
public static void main(String[] args) {
}
int sum = 0; //設為全域性變數這樣不會在呼叫過程中釋放
public int sumNumbers(TreeNode root) {
if(root == null) //遇到空節點時,就返回.注意每個葉子節點的左右節點都為空節點
return sum;
if(root.left == null && root.right == null) { //葉子節點,就把現在葉子節點的值(其實是路徑上計算過來的結果)加到sum變數中
sum +=root.val;
}
if(root.left != null)
root.left.val += root.val*10; //當左子節點不為空,則計算結果替換左子節點的值
if(root.right != null)
root.right.val += root.val*10; //當右子節點不為空,則計算結果替換右子節點的值
sumNumbers(root.left); //遞迴對左子節點,直到遇到空節點為止
sumNumbers(root.right); //遞迴對右子節點,直到遇到空節點為止
return sum;
}
}