376. 두 갈래 나무의 경로와
두 갈래 트리를 지정하고 모든 경로에서 각 노드가 합쳐져 목표 값을 지정하는 경로를 찾아냅니다.루트 노드에서 잎 노드까지의 경로를 가리키는 유효한 경로
예제
두 갈래 트리와 목표치 = 5:
             1
            / \
           2   4
          / \
         2   3
 :
        [
          [1, 2, 2],
          [1, 4]
        ]
생각
두 갈래 트리를 훑어보고 현재 결점 값을 경로에 추가하고 잎사귀 결점을 훑어보고 모든 완전한 경로를 얻을 수 있습니다. 경로의 각 점 값이 target에 충족되는지 판단하고 조건에 맞는 경로를 Result에 추가합니다.
코드
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    public List> binaryTreePathSum(TreeNode root, int target) {
        List> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        
        ArrayList path = new ArrayList<>();
        path.add(root.val);
        helper(root, path, root.val, target, result);
        return result;
    }
    
    private void helper(TreeNode root,
                        ArrayList path,
                        int sum,
                        int target,
                        List> result) {
        if (root.left == null && root.right == null) {
            if (sum == target) {
                result.add(new ArrayList(path));
                return;
            }
        }
        
        if (root.left != null) {
            path.add(root.left.val);
            helper(root.left, path, root.left.val + sum, target, result);
            path.remove(path.size() - 1);
        }
        
        if (root.right != null) {
            path.add(root.right.val);
            helper(root.right, path, root.right.val + sum, target, result);
            path.remove(path.size() - 1);
        }
    }
} 
  
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.