题解 | #二叉树根节点到叶子节点的所有路径和#

二叉树根节点到叶子节点的所有路径和

https://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        int result = 0;
        if (root == null)
            return result;
        if (root.left == null && root.right == null)
            return root.val;
        while ((root.left != null && root.left.val != -1) || (root.right != null &&
                root.right.val != -1)) {
            int value = getLeftChildernNode(root);
            result += value;
        }
        return result;
    }

    private int getLeftChildernNode(TreeNode treeNode) {
     TreeNode cur = treeNode;
        StringBuilder sb = new StringBuilder();

        sb.append(cur.val);
        //一致往下走,先左后右,直到叶子结点
        while (cur.left!=null || cur.right!=null) {
           if(cur.left!=null && cur.left.val!=-1) { //往左走
               cur=cur.left;
               sb.append(cur.val);
           }else if (cur.right!=null && cur.right.val!=-1) { //往右走
               cur = cur.right;
               sb.append(cur.val);
           }else { //叶子结点已经被遍历过了,被裁切掉了
               break;
           }
           
        }
        cur.val=-1; //当前结点值为-1 ,代表将该结点从树上裁掉

        if (cur.right==null && cur.left==null){ //只有当前结点是跟结点返回的值才有效
            System.out.println(sb.toString());
            return Integer.valueOf(sb.toString()).intValue();
        }else{
            return 0;
        }

    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务