129. Sum Root to Leaf Numbers(深搜、遞歸)

package Depth_first_Search;

public class SumNumbers_129 {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
	int sum;
	int total;
	public int sumNumbers(TreeNode root) {
		
		recur(root);
		return total;

	}

	private void recur(TreeNode root) {
		if(root!=null) {
			sum=sum*10+root.val;
			if(root.left==null&&root.right==null) {
				total+=sum;
			}
			recur(root.left);
			recur(root.right);
			sum=sum/10;
		}
	}

}

發佈了93 篇原創文章 · 獲贊 8 · 訪問量 9048
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章