Leetcode 1469. Find All the Lonely Nodes

Leetcode 1469. Find All the Lonely Nodes

Java Recursive

class Solution {
    List<Integer> ans = new ArrayList<>();
    
    public List<Integer> getLonelyNodes(TreeNode root) {
        helper(root);        
        return ans;
    }
    
    private void helper(TreeNode root) {
        if(root == null)
            return;
        if(root.left == null && root.right != null)
            ans.add(root.right.val);
        if(root.left != null && root.right == null)
            ans.add(root.left.val);
        
        helper(root.left);
        helper(root.right);
    }
}

python solution easy to understand

class Solution:
	def getLonelyNodes(self, root: TreeNode) -> List[int]:
		res = []
		def dfs(node):
			if node:
				if node.left and not node.right:
					res.append(node.left.val)
				if node.right and not node.left:
					res.append(node.right.val)
				dfs(node.left)
				dfs(node.right)
		dfs(root)
		return res

你可能感兴趣的:(递归,Leetcode,Tree)